Bash

From Piszczynski

Handy Bash commands

1. Force the system to check all file systems at boot:

sudo touch /forcefsck


2. Use cat to create or append text files;

cat > myfile.txt — Creates small text file. Use Ctrl+D to send text to file.

cat >> myfile.txt — Appends lines to bottom of pre-existing file.


3. Use pushd and popd to put move directories on and off of a stack.

pushd /directory — Moves to new directory.

popd — brigs you back to original directory


4. Open new root bash environment:

sudo bash — Use “exit” to return to your onw shell.


5. Make bash execute one command as root:

sudo bash -c “echo ‘QT_QPA_PLATFORMTHEME=gtk2’ >> /etc/environment” — Note: “sudo echo” at a command prompt will not work.


6. Use wget to download files from the internet:

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb — Downloads Google Chrome installer package into the current directory.


7. Automaticallly look for and install packages in a script:

dpkg -l | grep -qw gdebi || sudo apt-get install -yyq gdebi — Install gdebi packaage if it is not already installed.


8. Hide your cursor:

tput civis — Hides cursor.

tput cnorm — Brings cursor back.


9. Fix a terminal that’s gone crazy:

. .profile — Reloads your environment.

reset — resets the terminal completely.


9. Find a command in history:

Ctrl+R — Activates history search: Start typing to search for text. Pressing enter without typing will exit search.

— Note: Pessing Ctrl+S will turn off input and output from X! Press Ctrl+Q to turn it nack on.


10. String commands together at promt as they would run in a script:

command 1; commnad 2; commnad 3; … — Runs one command after another regardless of any command’s exit code.


11. Change file permissions on entire directory of files:

find /path/to/directory -type f -exec chmod 644 {} \; — Note: Changing “type -f” to “type -d” will do the same for all directories in the specified directory.


12. Using ranges in commands:

/bin/df -h /dev/sd[a-z][1-9] 2>/dev/null — Lists only drive partitions when running the df command.

mkdir test{01..10} — Creates 10 numbered directories.


13. Catching and dumping unwanted keyboard input (Percy’s patch):

long-running-command; read -t 1 -n 10000 discard

14: Make bash script executable

chmod 555 <filename>

Find Command

Use find to get files of a 1033 bytes size that are not executable:

  • find . -type f -size 1033c ! -executable

Text Tools

Grep

Use Grep command to find strings in text. Useful for finding matches in logs etc:

Find and print the line containing the word:

  • grep <string to match> <file>

can use the -n option to show line number

can use the -m option to stop after a number of matches

use -o to only return matches to the string

use -a to treat binary file as text

uniq

Use to find unique lines or strings in text

Pipe text into command to get info, eg to get only unique occurances:

  • cat <textfile> | sort | uniq -u