Common shell script commands

Time:2021-4-15

We need to learn to use tools to free our hands. For example, we can create soft links for some files in the folder in batch. We can write a script to implement it. Here are some commands used in this project.

variable

When defining a variable, the variable name is not marked with dollar

your_name="12"

Using variables

To use a defined variable, just add the dollar sign in front of the variable name

your_name="qinjx"
echo $your_name
echo ${your_name}

Curly braces outside the variable name are optional, and can be added or not. Curly braces are added to help the interpreter identify the boundary of the variable

Get the name of the folder / file in a directory

  1. If deep traversal is required, that is, the output folder already contains the files / folders in the folder, the command is as follows
#!/bin/bash
CD target directory
for file in $(ls *)
do
   echo $file
done
  1. If you only want to get the files of the first layer already in the folder, the following is true
#!/bin/bash
CD target directory
for file in $(ls )
do
   echo $file
done

Judgment of folder and file

The first grammar to judge is
if [ condition ]
Two commands:

  1. -F “file”: judge whether the file is a file;
  2. -D “file”: judge whether the file is a directory (folder).

Combined with the syntax of getting files / folders, for example, to determine whether a folder can be written like this

#!/bin/bash
CD target directory
for file in $(ls )
do
   if [ -d "$file" ]; then

     echo "$file is a directory "

   elif [ -f "$file" ]; then

     echo "$file is a file"  
   fi
done

Does the array contain a value

We know that JavaScript can be used directly[].includes('xxx'). In shell, you can write as follows:

if [[ " ${array[@]} " =~ " ${value} " ]]; then
  echo true
fi
if [[ ! " ${array[@]} " =~ " ${value} " ]]; then
  echo false
fi

Process control

If statement

if condition
then
    command1 
    command2
    ...
    commandN 
fi

if else

if condition 
then
    command1 
    command2
else 
    command
fi

if else-if else

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

Get the absolute path of a file

  1. To get the absolute path of a file, you can use the
$(pwd)
  1. If you want to get an absolute path to a relative file, you can write like this
$(cd ${basePath}; pwd)