Bash Scripts

Redirect stdout/stderr

redirect stdout/stderr

1
a.out 0<input.txt 1>out.txt 2>&1
  • a.out is executable
  • input.txt replaces standard input (0)
  • out.txt receives the redirected standard output (1) that would have gone to the screen
  • &1 (location of stdout) receives the redirected stderr (2) that would have gone to the screen

Ignore stdout

1
a.out 1>/dev/null

Ignore stderr

1
a.out 2>/dev/null

Chaining Commands

1
2
3
4
5
6
7
8
9
10
11
12
$ true; echo "sup"
sup
$ false; echo "sup"
sup

$ true && echo "sup"
sup
$ false && echo "sup"

$ true || echo "sup"
$ false || echo "sup"
sup

Awk a CSV Column

1
awk -F "'*,'*" '{print $3}' filename.csv | uniq | wc -l

Trim Alias

1
alias trim="awk '{\$1=\$1;print}'"

Usage:

1
grep --no-filename 'xsd:restriction' *.xsd | trim | sort | uniq

SSH With Expect

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/expect -f

set timeout 15
set force_conservative 1
set addr [lindex $argv 0]
set storenum [lindex $argv 1]

spawn ssh my_id@$addr
set session $spawn_id
expect "Password:"
send "my_password\r"
expect -exact "\$ "
send "...

FTP With Expect

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    #!/usr/bin/expect -f


    set addr [lindex $argv 0]
    set timeout -1
    spawn ftp $addr
    expect {
    "):" { send "my_username\r" }
    "timed" exit
    }
    expect {
    "d:" { send "my_password\r" }
    "ftp>" { send "\r" }
    }
    expect "ftp>"
    send "bin\r"
    expect "ftp>"
    send "hash\r"
    expect "ftp>"
    send "cd my_directory\r"
    expect "ftp>"
    send "put myfile\r"
    expect "ftp>"
    send "by\r" 

Threading Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
mkdir locations
uudecode $0
chmod 777 filename.exe
for entry in $LIST
do
ip=`echo $entry | awk -F \: '{print $2}'`
loc=`echo $entry | awk -F \: '{print $1}'`
logfile="./locations/$loc.log"
./filename.exe $ip > $logfile &
count=`ps -ef | grep -i exp | wc -l | awk '{print $1}'`
while [ $count -gt 100 ]
do
count=`ps -ef | grep -i exp | wc -l | awk '{print $1}'`
echo "waiting for process to finish"
done
sleep 2
done
exit 0
begin 777 check_stores.exp
###... UUENCODED CODE GOES HERE ...###

###... filename.exe is here ...###

###... in this case ...###

...
end
  • The & after executing allows you to continue without waiting for completion.
  • filename.exe executed can be any program type (sh, exp, c, cpp, py, etc) but should be uniq.
  • filename.exe doesn’t need to be uuencoded into the script but it’s useful if execution isn’t on your box.

Default Shell

Set

1
chsh -s /bin/bash

Verify

1
ps -p $$

Bash Alternative

Using tcsh instead of bash?

Use vi on command line

bash

1
set -o vi

tcsh

1
bindkey -v

Adding an alias

bash

1
alias vi='vim'

tcsh

1
alias vi 'vim'