function last_cmd_status() if [ $? -eq 0 ] # Space at out of '[]' then echo"success" elif [ $? -eq 1 ] then echo"failed,code is 1" else echo"other code" fi
The most-used command in history so far
1 2 3
history | awk 'BEGIN {FS="[ \t]+|\\|"} {print $3}' | sort | uniq -c | sort -nr | head
find -iname "xxx[abcd]*" -type f -mtime +1 # (File's data was last modified n*24 hours ago.)
string1="Ubuntu" string2="Pit" string=$string1$string2 echo"$string is a great resource for Linux beginners." # "UbuntuPit is a great resource for Linux beginners." to the screen.
Slicing Strings
1 2 3 4 5 6
#!/bin/bash Str="Learn Bash Commands from UbuntuPit" subStr=${Str:0:20} echo$subStr
${VAR_NAME:S:L}. Here, S denotes starting position and L indicates the length.
Extracting Substrings Using Cut
1 2 3 4 5 6
#!/bin/bash Str="Learn Bash Commands from UbuntuPit" #subStr=${Str:0:20}
subStr=$(echo$Str| cut -d ' ' -f 1-3) echo$subStr
Function with return
1 2 3 4 5 6 7 8 9 10 11 12
#!/bin/bash
functionGreet() { str="Hello $name, what brings you to UbuntuPit.com?" echo$str }
ls -lrRt | grep ^- | awk 'END{print $NF}' # "^-" : '-' is start of lines, so means files.
Adding Batch Extensions
1 2 3 4 5 6
#!/bin/bash dir=$1 for file in `ls$1/*` do mv$file$file.UP done
Print Number of Files or Directories
1 2 3 4 5 6 7 8 9
#!/bin/bash
if [ -d "$@" ]; then echo"Files found: $(find "$@" -type f | wc -l)" echo"Folders found: $(find "$@" -type d | wc -l)" else echo"[ERROR] Please retry with another folder." exit 1 fi
find . -mtime -1 -type f -print0 | xargs -0 tar rvf "$archive.tar" echo"Directory $PWD backed up in archive file \"$archive.tar.gz\"." exit 0
Check Whether You’re Root
1 2 3 4 5 6 7 8 9 10
#!/bin/bash ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ] then echo"You are root." else echo"You are not root" fi exit 0
Removing Duplicate Lines from Files
1 2 3 4 5 6 7 8 9 10 11
#! /bin/sh
echo -n "Enter Filename-> " read filename if [ -f "$filename" ]; then sort$filename | uniq | tee sorted.txt else echo"No $filename in $pwd...try again" fi exit 0 # The above script goes line by line through your file and removes any duplicative line. It then places the new content into a new file and keeps the original file intact.