Write a script

  1. Find a place to create a new file with whatever suffix you want, generally the script suffix is.sh. I like to put scripts in the ~/local directory.
    1. mkdir ~/local
    2. cd ~/local
    3. touch demo.txt
  2. Edit demo.txt as follows:
     mkdir demo
     cd demo
     mkdir css js
     touch index.html css/style.css js/main.js
     exit
    Copy the code
  3. Add execute permission to demo.shchmod +x demo.txt
  4. Execute at any locationsh ~/local/demo.txtYou can run the script
    1. cd ~/Desktop
    2. sh ~/local/demo.txt
    3. You will see that there is a demo directory in the current directory, and there are some files in the demo directory. Ok, this demo. TXT is the first Bash script you wrote: vi ~/
  5. Add ~/local to PATH
    1. cd ~/local; pwdI get the absolute path to local
    2. Create a ~ /. Bashrc:touch ~/.bashrc
    3. Edit the ~ /. Bashrc:start ~/.bashrc, added in the last lineExport PATH="local absolute PATH :$PATH"
    4. source ~/.bashrc
    5. Before you have to runsh ~/local/demo.txtNow all you need to do is run demo.txt (see why).
  6. The suffix.txt for demo.txt is boring, delete it
    1. mv ~/local/demo.txt ~/local/demo
    2. Now you just rundemoYou can execute the script.

details

  1. Every time you type a command in Bash (ls, cp, demo), Bash looks for the file in the PATH list and executes it if it finds one.
  2. Use type Demo to see the search process, step by step
  3. Using the Which demo you can see the search results, only the results
  4. What file suffixes do: Nothing

parameter

Demo scripts can only create directories named demo, which is boring, so let’s make the directory name variable.

mkdir The $1
cd The $1
mkdir css js
touch index.html css/style.css js/main.js
exit
Copy the code

$1 is the first parameter you pass.

Sir, how do you know that $1 represents the first parameter?

Good question, and the answer is

I googled lmgtfy.com/?q=bash+fir… Use Baidu also www.baidu-x.com/?q=bash+%E7…

Check whether the directory already exists

if [ -d The $1 ]; then
  echo 'error: dir exists'
  exit
else
  mkdir The $1
  cd The $1
  mkdir css js
  touch index.html css/style.css js/main.js
  echo 'success'
  exit
fi
Copy the code

Teacher, how do you know -d $1 can tell if the directory exists?

I googled lmgtfy.com/?q=bash+dir…

The return value

  • exit 0No errors
  • exit 1The error code is 1
demo && echo 'the end'
Copy the code

Echo ‘end’ will only be executed if demo is successful