Welcome to weblogs.com.pk Sign in | Join | Help

Bash

She-Bang, Kernel uses this information when calling execve(2) syscall

#!/bin/bash

Variables

  • https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html for built in variables like BASH_ARGV, HOSTNAME and PWD etc
#bash don't like spaces here
a=123
echo "The value of a is $a"
#No need of newline; it happens automatically
echo Your name
read NAME
echo Hello $NAME

Functions

function juju {
  local a = 321
  echo $a
}
function hi {
  echo "Hello $1"
}
juju
hi Khurram

Conditions

#we can have spaces in condition
if [ a = 123]; then
  echo "a is 123"
elif [ a = 321]; then
  echo "a is 321"
else
  echo "a is neither 123 nor 321"
fi
if [ "$a" = "123" ]; then
  echo "a is still 123 as string"
else
  echo "a is not 123"
fi

Loops

#its not single quote; its `
for i in `seq 1 10`;
do
  echo $i
done
for j in $( ls ); do
  echo $j
done
k=0
while [ $k -lt 10 ]; do
  echo $k
  let k=k+1
done
l=10
until [ $l -gt 0 ]; do
  echo $l
  let l-=1
done

Bash Specific: Menu; it will print 1) Hi, 2) Bye, and pressing 1 or 2 will proceed accordingly

options="Hi Bye"
select opt in $options; do
  if [ "$opt" = "Hi" ]; then
    echo "Hello World"
  else
    exit
  fi
done

Command line arguments

#$0 is script and $1 is first argument
if [ -z "$1" ]; then
  echo usage: $0 directory
  exit
fi

Return value of another program

cd /juju &> /dev/null
echo $?
#will print 1; if /juju doesn't exist
cd $(pwd) &> /dev/null
echo $?
#will print 0; as pwd exists

Capture command output

dbs='MySQL -u root -e "show databases"
for d in dbs;
do
  MySQL -uroot -e "show tables from $b"
done
Published Friday, March 03, 2017 8:09 PM by khurram
Filed under:

Comments

No Comments

New Comments to this post are disabled