Common Shell Commands Cheatsheet

 
  1. Beginning of the .sh files
    #!/bin/sh
    # Must be put at the beginning of the .sh file
    
  2. Create directory
    mkdir $dir_name
    

    If the directory existed, commands in the following steps will be stopped and warning will be sent.

  3. Create directory with parents directories
    mkdir -p $dir_name
    

    If the directory existed, command in the following steps will not be stopped.

  4. Find a file (f) / directory (d) with specific keywords and copy it to a directory
    find $search_dir -maxdepth $search_depth$ -type $f or d$ -name $keyword(*) -exec cp '{}' $target_dir \;
    
    • If the keyword is not strictly refined, * could be added after the keyword.
    • The last backslash \ could not be missed.
  5. Variables
    # A random example to assess the subdirectory called Deep_learning_task
    mission_name=Deep_learning_task
    cd "../$mission_name"
    
    # variable evaluation
    num_start=0
    num_end=5
    run_time=$(num_start+num_end)
    
    • No space in the variable mission_name
    • Modified strings have quotation mark “”
    • Variable evaluation is also possible
  6. Condition syntax
    if [ expression ]
    then
    Statement(s) to be executed if true
    else
    Statement(s) to be executed if not true
    fi
    
  7. Loop control
    NUMS="1 2 3 4 5 6 7"
    for NUM in $NUMS
    # for ((NUM=1; NUM< 8; NUM++))
    do
    Q=`expr $NUM % 2`
    if [ $Q -eq 0 ]
    then
       echo "Number is an even number!!"
       continue
    fi
    echo "Found odd number"
    done
    
  8. Print
    echo "I am an echo function"
    
  9. Copy files
    cp $current_file $future_dir
    
    • With parent directories
      cp --parents $current_file $future_dir
      
    • copy directory
      cp -r $current_file $future_dir
      
  10. Replace keyword
    sed -i "s/$search_keyword/$new_keyword/" $operated_file
    
    • Please don’t forget s and three /
  11. Compress and decompress
    tar [options] [archive-file] [file or directory to be archived]
    

    Options:

    • c : Creates archive
    • x : Extracts the archive
    • f : creates archive with given filename
    • v : Displays verbose information
# decompress
tar xfv $target_tar_file
# compress
tar cfv $target_tar_file $to_compress_dir1 $to_compress_dir1