Introduction
the shell environment helps users to interact with and access core function of the operation system
A shell script is a text file that typically begins with a shebang(工作), as follows:
#!/bin/bash
#Filename: xxx.sh
run:
1. bash xxx.sh
2. ./xxx.sh (executable permission)
Printing in the terminal
echo -e "string containing escape sequences(转义字符)"
echo "welcome to bash"
echo -e "1\t2\t3"
echo -e "\e[1;32m This is green text;\e[0m"
Play with variables and environment variables
the value for every variable is string
printing contents of a variable is done by using prefixing $ with the variable name as follows:
message="can you see me?"
echo $message
finding the length of a string
var=123456789
echo ${#var}
dentifying(识别) the current shell
echo $0
Math with the shell
bc:
echo "4*0.56" | bc
no=54
result=`echo "$no * 1.5" | bc`
echo $result
#Decimal places scale with bc
echo "scale=2;3/8" | bc
#Base conversion with bc
no=100
echo "obase=2;$no" | bc
mo=1100100
echo "obase=10;ibase=2;$mo" | bc
echo "10^10" | bc
Play with file descriptor and redirection
descriptors | data stream | device |
---|---|---|
0 | stdin | keyboard |
1 | stdout | screen |
2 | stderr | screen |
symbol | meaning |
---|---|
> | stdout redirect |
>> | stdout append |
< | stdin redirect |
<< | stdin append |
stdout:
#empty content before writing
echo "This is a simple test1" > temp.txt
#append text to a file
echo "This is a simple test2" >> temp.txt
cat temp.txt
stderr:
ls + 2>stderr.txt
stderr & stdout:
#redirect stderr exclusively(唯一的,专有的) to a file and stdout to another file
cmd 2> stderr.txt 1> stdout.txt
#redirect stderr and stdout to a single file
cmd &> stdout.txt
the tee command can read from stdin only
command | tee File1 File2
#empty,'cat -n' puts a line number for each line received from stdin and write it into stdout
cat xx | tee out.txt | cat -n
#append
cat xx | tee -a out.txt | cat -n
Arrays and associative arrays
see the book
associative arrays equal to dictionary
Visiting aliases
alias new_command=`command sequence`
#example
alias install=`sudo apt-get install`
the alias command is temporary; aliasing exiting until we close the current terminal only. To keep the shortcut permanent, add this statement to the ~/.bashrc file.(利用重定向写入bachrc文件)
echo 'alias cmd="command seq"` >> ~/.bashrc