Friday, October 11, 2013

Everyday Shell Scripts

  • Rename the extensions of all files,

    for FILE in *.foo ; 
    do NEWFILE=`echo $FILE | sed 's/.foo/.bar/g'` ;
     mv "$FILE" $NEWFILE ; 
    done
  • Test if a variable is set (pay attention to the space, they can't be eliminated),

    if [ ! -z "$var" ]; then
      echo "var exists"
    fi
  • Test if a file exists,

    if [ -f "$file" ]; then
      echo "file exists"
    fi
  • Copy one file to the clipboard (install xclip first)

    cat file | xclip -selection c
  • Paste clipboard to a file

    xclip -o > file
  • Define a function

    foo(){
      echo "FUNCTION"
    }
    fun=$(foo)
    
  • The most recent foreground pipeline exit status: $?

    if [ $? -eq -1 ]
      then
      exit 1
    fi 
  • Several ways of for loop controlled by a var

    for I in {1..10}; do echo $I; done
    for I in 1 2 3 4 5 6 7 8 9 10; do echo $I; done
    for I in $(seq 1 10); do echo $I; done
    for ((I=1; I <= 10 ; I++)); do echo $I; done
  • Generate ticks in (-4pi, 4pi):

    for i in $(seq -4 4); do b=`echo "$i * 3.14159" | bc`; echo -ne $b","; done; 

    This is useful for PGFplots for trigonometric ticks,

    xtick={-12.56636,-9.42477,-6.28318,-3.14159,0,
    3.14159,6.28318,9.42477,12.56636},
    xticklabels={
            $-4\pi$, $-3\pi$, $-2\pi$, $-\pi$, $0$,
            $\pi$, $2\pi$, $3\pi$, $4\pi$
     }
  • Convert all jpeg files and save them as png files.

    for file in *.jpg;do 
      newfile=`echo $file | sed 's/.jpg/.png/g'`;
      gm convert -quality 60 $file $newfile;
    done
  • Compress all jpeg files.

    mkdir new
    for file in *.jpg;do 
      newfile="new/$file";
      gm convert -quality 60 $file $newfile;
    done

No comments:

Post a Comment