Snippets
Leer una entrada
echo -n "Proceed? [y/n]: "
read -r ans
echo "$ans"
Condicionales
if ping -c 1 google.com; then
echo "It appears you have a working internet connection"
fi
if grep -q 'ping' ~/.bash_history; then
echo "Tu escribiste 'ping' alguna vez."
fi
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-V | --version )
echo "$version"
exit
;;
-s | --string )
shift; string=$1
;;
-f | --flag )
flag=1
;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
Case switch
case "$1" in
start | up)
vagrant up
;;
*)
echo "Usage: $0 {start|stop|ssh}"
;;
esac
Realizar operaciones
$((a + 200)) # Add 200 to $a
$(($RANDOM%200)) # Random number 0..199
declare -i count # Declare as type integer
count+=1 # Increment
# String
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
else
echo "This never happens"
fi
# Combinations
if [[ X && Y ]]; then
...
fi
# Equal
if [[ "$A" == "$B" ]]
# Regex
if [[ "A" =~ . ]]
if (( $a < $b )); then
echo "$a is smaller than $b"
fi
if [[ -e "file.txt" ]]; then
echo "file exists"
fi
Parámetro | Significado |
---|---|
$? | Exit status of last task |
$! | PID of last background task |
$$ | PID of shell |
$0 | Filename of the shell script |
$_ | Last argument of the previous command |
${PIPESTATUS[n]} | return value of piped commands (array) |
Instruccón | Significado |
---|---|
[[ -e FILE ]] | Exists |
[[ -r FILE ]] | Readable |
[[ -h FILE ]] | Symlink |
[[ -d FILE ]] | Directory |
[[ -w FILE ]] | Writable |
[[ -s FILE ]] | Size is > 0 bytes |
[[ -f FILE ]] | File |
[[ -x FILE ]] | Executable |
[[ FILE1 -nt FILE2 ]] | 1 is more recent than 2 |
[[ FILE1 -ot FILE2 ]] | 2 is more recent than 1 |
[[ FILE1 -ef FILE2 ]] | Same files |
[[ -o noclobber ]] | If OPTIONNAME is enabled |
[[ ! EXPR ]] | Not |
[[ X && Y ]] | And |
[[ X or Y ]] | Or |
[[ -z STRING ]] | Empty string |
[[ -n STRING ]] | Not empty string |
[[ STRING == STRING ]] | Equal |
[[ STRING != STRING ]] | Not Equal |
[[ NUM -eq NUM ]] | Equal |
[[ NUM -ne NUM ]] | Not equal |
[[ NUM -lt NUM ]] | Less than |
[[ NUM -le NUM ]] | Less than or equal |
[[ NUM -gt NUM ]] | Greater than |
[[ NUM -ge NUM ]] | Greater than or equal |
[[ STRING =~ STRING ]] | Regexp |
(( NUM < NUM )) | Numeric conditions |
Enlaces: