Write a script
- 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.
mkdir ~/local
cd ~/local
touch demo.txt
- 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
- Add execute permission to demo.sh
chmod +x demo.txt
- Execute at any location
sh ~/local/demo.txt
You can run the scriptcd ~/Desktop
sh ~/local/demo.txt
- 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 ~/
- Add ~/local to PATH
cd ~/local; pwd
I get the absolute path to local- Create a ~ /. Bashrc:
touch ~/.bashrc
- Edit the ~ /. Bashrc:
start ~/.bashrc
, added in the last lineExport PATH="local absolute PATH :$PATH"
- source ~/.bashrc
- Before you have to run
sh ~/local/demo.txt
Now all you need to do is run demo.txt (see why).
- The suffix.txt for demo.txt is boring, delete it
mv ~/local/demo.txt ~/local/demo
- Now you just run
demo
You can execute the script.
details
- 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.
- Use type Demo to see the search process, step by step
- Using the Which demo you can see the search results, only the results
- 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 0
No errorsexit 1
The error code is 1
demo && echo 'the end'
Copy the code
Echo ‘end’ will only be executed if demo is successful