Shell Programming for Getting Started with Linux

variable

nano hello.sh edit the shell script file hello.sh, such as write echo 'hello!!!'. Among them, adding #!/bin/bash at the very beginning of editing means that the script file is executed with bash, # is a comment, #! is not a comment.

bash/source/.hello.sh execute hello.sh, such as output hello!!!

name=zs defines the user-defined variable name

echo $name outputs the value of the user-defined variable as zs

env View environment variables

export name turns the name user-defined variable into an environment variable

readonly name Set the name variable to read-only

unset name clears the name variable

current_dir=$(pwd) assign the result of pwd execution to current_dir, or current_dir=`pwd` (backtick).

read name Input name from the keyboard (read -p "Please input your name:" name prompts the keyboard to enter name).

read name1 name2   other  input multiple variables, other is used to store multiple input variables

echo -e "zs\nzss" plus -e to handle escape characters

echo -n "zs" plus -n cancels the default newline at the end

variable calculation

comparison of numbers

Integer calculation

expr $a + $b calculates a+b, because linux defaults to strings, so it cannot be directly calculated (note that if it is greater than \>, multiplication must be escaped with \*).

c=`expr $a + $b` assigns the calculation result to c through command substitution

c=$((a + b)) or let c=a+b calculate a+b and assign it to c (here operator + can be added or not before and after)

floating point calculation

c=$(echo "$a+$b" | bc) uses the pipeline to calculate the floating-point number a+b for bc, or write bc separately and calculate the floating-point number while reading.

c=`echo "$a+$b" | bc` can be replaced by the backtick command to calculate the floating point number a+b and then assign it to c

string comparison

logic operation

with: -a / && , or: -o / ||

move left

shift 1 shifts the variable to the left by 1, for example, $2 becomes $1, $3 becomes $2, and so on ( $1 and so on are position parameters , and $? stores the return value ).

string split

set -- -rw-r--r-- 1 root root 10272 May 25 10:34 /etc/passwd After execution, $1 is -rw-r--r--, $2 is 1, $3 is root, and so on.

branch structure

if [ $a -ge $b ] then ... fi or if test $a -ge $b then ... fi There must be spaces in the brackets, that is, if(a>=b){...} in c.

if [ $a -ge $b ] then ...elif [condition];then...else...  fi then is { in c, fi is }, and then should be preceded by ;.

if ((x%2==0)) judges whether x is an even number ( (( expression )) is used for numerical comparison and operation).

if [ -d "$file_name" ] determines whether the given file file_name is a directory .

Here are some commonly used file test operators :

  • -e file: Determine whether the file exists
  • -f file: Determine whether the file is an ordinary file
  • -d file: Determine whether the file is a directory
  • -r file: Determine whether the file is readable
  • -w file: Determine whether the file is writable
  • -x file: Determine whether the file is executable
  • -s file: Determine whether the file size is greater than 0
  • -h file: Determine whether the file is a symbolic link

  Program example: multi-choice statement, analogous to switch ... case.

#!/bin/sh

site="runoob"

case "$site" in
   "runoob") echo "菜鸟教程"
   ;;
   "google") echo "Google 搜索"
   ;;
   "taobao") echo "淘宝网"
   ;;
   *) echo "以上都不是"
   ;;
esac

loop structure

for i in zs lisi do...done loops twice, the first i is zs, the second i is lisi, there is a newline before do, analogous to python's for.

for i in `seq 1 2 10` do...done is a cycle from 1 to 10 with a step size of 2, and if 2 is deleted, the step size is 1, which is similar to range but this closed interval.

for i in {1..10}; do...done Use {1..10} to generate an integer sequence from 1-10, that is, i is 1-10.

Program example: The for loop can also be (( expression )) , the following is the sum of the first n items of 1+22+333+4444+….

#!/bin/bash

read n
sum=0
for ((i=1; i<=n; i++));do
    value=i
    for ((j=2;j<=i;j++));do
        value=$((value*10+i))
    done
    sum=$((sum+value))
done
echo $sum

Program example: read command line parameters ( $* represents all command line parameters ).

#假设脚本名为hello.sh(注意输入在只有一行)
# 输入:. hello.sh 2 2 3 6 3
# 输出:16
sum=0
for i in $*
do
 let sum=sum+i
done
echo $sum

Program example: while loop example.

#!/bin/bash
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

 Program example: example of eternal cycle.

#写法一
while :
do
    command
done

#写法二
while true
do
    command
done

#写法三
for (( ; ; ))

Replenish:

The until loop executes a series of commands until the condition is true (just the opposite of the while loop).

The loop also has the same break and continue as C++ .

array

Program example: array definition, input and access traversal.

# 定义数组
arr=(value1 value2 value3)

# 从标准输入读取多个值,并存储到数组中
read -a arr

# 访问数组元素
echo "${arr[0]}"  # 输出 value1
echo "${arr[1]}"  # 输出 value2
echo "${arr[2]}"  # 输出 value3

# 遍历数组,用${arr[@]}获取数组长度
for i in "${arr[@]}"; do
  echo "$i"
done



# 将一组数据直接读入然后遍历字符串每个空格隔开的值也像遍历数组一样
read str
for i in $str
do
    echo $i
done

function

Program example: function transfer and return value.

#!/bin/bash

fun(){
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !" #当n>=10时,需要使用${n}来获取参数
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
    return 123
}
fun 1 2 3 4 5 6 7 8 9 34 73
echo $? #函数返回值在调用该函数后通过 $? 来获得

Guess you like

Origin blog.csdn.net/weixin_61725823/article/details/130962598