Beneficial Bash

18 February 2015 Contribute to this post

Not really just the most frequently used commands of Bash, but more a list of thing I found beneficial at some point. Thing I know Iā€™d need to reuse again later.

CTRL e          Move cursor to end of line
CTRL a          Move cursor to beginning of line
CTRL u          Delete from cursor until beginning of line
CTRL k          Delete from cursor until end of line
CTRL l          Clear screen
pwd             Current directory name
ssh             Log on to a different server
scp             Copy files across servers

Rename all png files in a directory, add _test to the filename:

for file in *.png; do mv "$file" "${file/.png/_test.png}"; done

To remove _test from the filename, do this:

for file in *.png; do mv "$file" "${file/_test.png/.png}"; done

grep

Find the line with two words, when you know the order of the words in the line:

echo 11 tests, 4 failures | grep 'test.*failure'

Find multiple words:

echo 11 tests, 4 failures | grep -E 'test|failure'

Find word(s) in a file:

grep "some words" some-file.log

curl

Get source code from url:

curl -s http://ap-advtool1s:8080/

sed

Replace. Add line breaks to output between each ā€˜><ā€™ in url source:

curl -s http://ap-advtool1s:8080/ | sed 's/></>\n</g'

curl/sed/grep

Get lines containing both a style and a class tag from url source:

curl -s http://ap-advtool1s:8080/ | sed 's/></>\n</g' | grep style= | grep class=

if else

When running scripts with arguments, make sure first argument is provided:

if [[ $1 != "" ]] 
then 
    echo Argument provided
else 
    echo Argument missing!
fi

Remove from beginning and end of a multiple-line output

To demonstrate, we use the command git remote -v (from inside a git repository), which will output two lines:

git remote -v
# origin http://server.git (fetch)
# origin http://server.git (push)

We pipe the output, grep the line containing the word push, and remove origin and (push) from it with sed:

git remote -v | grep push | sed -e 's/origin //g' -e 's/ (push)//g'
# http://server.git

Make file executable

Before you can execute a file, it must be executable:

chmod +x file.sh

Also, to make the file un-executable:

chmod -x file.sh

Change owner

chmod -R username:username /path/directory
# -R : Recursively

.bash_profile

export PATH="$PATH:/cygdrive/c/Users/ux2k/AppData/Local/Yarn/.bin"

alias rep='cd c:/Projects'
alias klar='cd c:/Projects/klar/Templated-Salary-Input'
alias gitup='git fetch origin ; git branch -v -a'
alias br='source ~/.bash_profile ;echo --- reloaded bash_profile'
alias killnode='taskkill /f /im node.exe'