my cheat bash (both linux and mac osx)…
1 Generic bash cheats:
2 Variables
2.1 Variables are assigned simply with the = sign
EDITOR=/user/local/bin/emacs
2.2 Variables are referenced using a $ prefix:
echo $EDITOR
2.3 variables in single vs double quotation marks:
You can use either single or double quoatation marks (tics or dirks). When you use dirks, any variable reference inside the dirks get expanded. When you use tics, the variable is treated not as a variable but as a literal string.
echo "My editor is $EDITOR" echo 'My editor is $EDITOR'
Results in this output:
My editor is /usr/local/bin/emacs My editor is $EDITOR
2.4 Uppercase and Lowercase a String
It is very easy to convert a string to upper or lower case in bash.
the ,,
and ^^
operators do it as shown in this example:
a = "Hello World" echo $a # will show "Hello World" echo "${a}" # will show "Hello World" echo "${a,,}" # will show "hello world" echo "${a^^}" # will show "HELLO WORLD"
Notice, that this works on my Linux bash shell, but does NOT work on my
darwin mac osx bash shell. I get a bash: ${a^^}: bad substitution
error.
That is because my Linux is running BASH 4.0 (4.4.20(1)
actually) where my
macbook pro is running BASH 3.2.57(1)
For my macbook I can do this: (courtesy of stackoverflow.com )
3 bash functions
If you want to create an alias
that also accepts one of more arguments
, the
easiest way is to use bash functions
:
function_name () {
[commands]
}
Or (these two do the exact same thing, just the syntax is different.
function function_name { [commands] }
To pass one or more arguments to the function, just call the function with
the arguments separated by spaces
. For example mult 55 2.54
if you had
created a function "mult" that multiplied two numbers, so in this case 55*2.54
would be returned.
While creating/writing the function, the arguments are assigned to variables
$1, $2, $3, $4
etc…
So my mult function would look like this:
mult() { echo "$1" * "$2" }
And,
mkcd () { mkdir -p -- "$1" && cd -P -- "$1" }
3.1 Special bash reserved variables
A couple of reserved variables that are useful:
$0 | The command you just entered |
$1 | first argument |
$2 .. $9 | second through 9th argument |
$_ | last argument |
$? | Error code from last command |
3.2 Codes from previous command
$? is the error code
3.3 A function example I got from … WHERE?
function myinfo { printf "\n" uname -a | awk '{ printf "Kernel: %s " , $3 }' uname -m | awk '{ printf "%s | " , $1 }' printf "\n" uptime | awk '{ printf "Uptime: %s %s %s", $3, $4, $5 }' | sed 's/,//g' printf "\" }
To use this later, just type myinfo()
3.4 Finally running bash for multiple files with sed.
for file in *.org sed 's/zintis AT gmail DOT com/zintis AT senecacollege DOT ca/' $file > $file.new end
check the results and if good:
for file in *.org.new mv "$file" "{$file%.new}.old" end
3.5 Bash script to traverse subdirectories
A common find command to list directories: find . -maxdepth 1 -type d -print
I can put that into a for loop to do something in each of these directories.
for d in $(find /path/to/dir -maxdepth 1 -type d) do #Do something, the directory is accessible with $d: echo $d done > output_file
Here is a concrete example I use when moving my html files to a target dir;
for d in $(find ~/eg -maxdepth 1 -type d) do mv $d/*.html ~/Documents/visada/exported-html echo $d done
4 Specific commands
4.1 cd
can use cd - to change to the previous directory
You can also use $OLDPWD, which is the old directory. That is always maintained by bash, so you can use it in scripts, or make an alias using cd $OLDPWD.
4.2 tree
Just like in Linux bash
4.3 ditto
To copy files and directories (duplicating them) you can use
-V
option for "verbose"
and the command: ditto -V /src-dir /dest-dir
For files it is ditto -V /src-dir/top-gun.mp4 /dest-dir
4.4 shopt -s cdspell
Makes common spelling corrections when using cd. So cd ~/Desktpo will actually catch the error and cd you to ~/Desktop
4.5 shopt -s autocd
If a command is not a valid command, autocd will check if the command is actaully the name of a directory, and if it is, will cd to that directory.
5 Environment variables
5.1 CDPATH
If I add export CDPATH=/Users/zintis/bin/python
to my .bashprofile
bash will check a matching directory in that path 1st and if a match
is found, will cd into that directory, saving you from having to type
cd ~/bin/python/bin instead letting you type cd bin
I can still cd into the absolute path, for example cd /usr/bin, but if I was in /usr then cd bin would NOT put me in /usr/bin but ~/bin/python/bin
Otherwise pretty useful if you spend a lot of time in ~/bin/python
5.2 Always show path in finder window
defaults write com.apple.finder _FXShowPosixPathInTitle -boolean true
This is entered via terminal, but really is for the finder gui windows.
5.3 Put screenshots in ~/Downloads, not ~/Desktop
defaults write com.apple.screencapture location ~/Downloads
5.4 Switch off dashboard
defaults write com.apple.dashboard mcx-disabled -boolean TRUE
5.5 curl
To download a file given an http url:
curl -O
5.6 stop your mac from sleeping
caffeinate -u -t 3600
won't sleep for 1 hour (3600 seconds)
caffeinate
won't sleep at all
5.7 uptime
obvious
6 MAC OSX powermetrics
man powermetrics
- To see CPU temperature:
sudo powermetrics --samplers smc | grep -i "CPU die temperature"
- To see GPU temperature:
sudo powermetrics --samplers smc | grep -i "GPU die temperature
" - To see network in/out :
sudo powermetrics -i 10000 --samplers network
- To see network in/out :
sudo powermetrics -i 10000 --samplers network | grep packets
Default is 5 seconds powermetrics -n 5 sets only 5 intervals to display. Default is 0 meaning infinite. powermetrics --show-initial-usage # since uptime powermetrics --show-usage-summary # final summary, before exiting powermetrics --show-all
7 symbolic links a.k.a. symlinks
ln -s original link
ln -s existing-file newlinktoexistingfile
ls -s /path/exiting-file
# leave off the 'new' link to create a new
rm link
Note that the original
file is NOT deleted
, only the symbolic link
to it.
7.1 symbolic link workflow
Assume you have a file called junk1 in a directory /x/y/z, so /x/y/z/junk1
- cd to a target directory that does not contain a file called junk1
cd /usr/local/bin
ln -s /x/y/z/junk1
will create a link in /usr/local/bin, namely:/usr/local/bin/junk1 -> /x/y/z/junk1
- The second form, in the /x/y/z directory:
ln -s junk1 junk2
will create a link in/x/y/z/junk2 -> /x/y/z/junk1
In the manual pages, i.e. man ln target
means the new symbolic link
which
in my mind is opposite. Just be ware of that.
ln -s existing-file target-directory
or
ln -s existing-file new-pointer-to-existing-file
ln -s existing-file symb-link-to-existing-file
so, for me this creates:
new-pointer-to-existing-file -> existing file
(kind of the reverse order that these were entered into the ln -s command)
Zintiss-MacBook-Pro-5:~] zintis% ln -s CAN-pricelist.txt pricelist [Zintiss-MacBook-Pro-5:~] zintis% lst total 207296 -rw-r--r--@ 1 zintis staff 45580288 4 Jan 10:44 CAN-pricelist.txt lrwxr-xr-x 1 zintis staff 17 4 Jan 10:44 pricelist -> CAN-pricelist.txt drwx------+ 133 zintis staff 4522 4 Jan 10:36 Documents drwx------+ 22 zintis staff 748 4 Jan 10:28 Downloads
ln -s source-file target-directory
Given one or two arguments, ln creates a link to an existing file
source_file
. If target_file
is given, the link has that name
;
targetfile may also be a directory in which to place the link
; otherwise
it is placed in the current directory. If only the directory is speci-
fied, the link will be made to the last component of sourcefile.
So to get ~/Movies
to point to an external drive do the following:
cd to ~/
ln -s /Volumes/WD-3TB-perkons/Movies/ Movies
then still in ~/ directory run:
ls -l
and you'll see:
[Zintiss-MacBook-Pro-2:~] zintis% pwd /Users/zintis [Zintiss-MacBook-Pro-2:~] zintis% ls -l . . . drwx------+ 143 zintis staff 4862 25 Jun 13:31 Documents drwx------+ 41 zintis staff 1394 28 Jun 13:04 Downloads drwx------@ 58 zintis staff 1972 13 May 10:38 Library lrwxr-xr-x 1 zintis staff 31 30 Jun 13:40 Movies -> /Volumes/WD-3TB-perkons/Movies/ drwx------+ 7 zintis staff 238 31 Mar 22:27 Music drwxr-xr-x 4 zintis staff 136 30 Aug 2011 NetApp drwx------+ 103 zintis staff 3502 3 May 13:57 Pictures drwxr-xr-x+ 6 zintis staff 204 22 Aug 2011 Public . . .
An example with output:
mkdir /Users/Shared/Pictures/iPhoto\ Library sudo ln -s /Users/Shared/Pictures/iPhoto\ Library/ /Users/user1/Pictures/iPhoto\ Library sudo ln -s /Users/Shared/Pictures/iPhoto\ Library/ /Users/user2/Pictures/iPhoto\ Library
Output:
cd /Volumes [rtp-zperkons-8717:/Volumes] zintis% pwd /Volumes [rtp-zperkons-8717:/Volumes] zintis% ls -la total 24 drwxrwxrwt@ 6 root admin 204 9 Dec 00:19 . drwxr-xr-x 33 root wheel 1190 9 Dec 01:36 .. -rw-r--r--@ 1 zintis admin 6148 25 Sep 21:07 .DS_Store lrwxr-xr-x 1 root admin 1 7 Dec 09:27 320GB-HItachi -> / drwxrwxrwx 0 root wheel 0 9 Dec 11:43 MobileBackups drwxrwxr-x 25 zintis staff 1326 9 Dec 11:23 WD-3TB-perkons [rtp-zperkons-8717:/Volumes] zintis% ln -s WD-3TB-perkons/ WD-1TB-partition [rtp-zperkons-8717:/Volumes] zintis% ls -la total 32 drwxrwxrwt@ 7 root admin 238 9 Dec 12:04 . drwxr-xr-x 33 root wheel 1190 9 Dec 01:36 .. -rw-r--r--@ 1 zintis admin 6148 9 Dec 12:04 .DS_Store lrwxr-xr-x 1 root admin 1 7 Dec 09:27 320GB-HItachi -> / drwxrwxrwx 0 root wheel 0 9 Dec 11:43 MobileBackups lrwxr-xr-x 1 zintis admin 15 9 Dec 12:04 WD-1TB-partition -> WD-3TB-perkons/ drwxrwxr-x 25 zintis staff 1326 9 Dec 11:23 WD-3TB-perkons [rtp-zperkons-8717:/Volumes] zintis%
And from ln man pages:
SYNOPSIS ln [-Ffhinsv] source_file [target_file] ln [-Ffhinsv] source_file ... target_dir link source_file target_file -s Create a symbolic link. By default, ln makes hard links. A hard link to a file is indistinguishable from the original directory entry; any changes to a file are effectively independent of the name used to reference the file. Hard links may not nor- mally refer to directories and may not span file systems. A symbolic link contains the name of the file to which it is linked. The referenced file is used when an open(2) operation is performed on the link. A stat(2) on a symbolic link will return the linked-to file; an lstat(2) must be done to obtain information about the link. The readlink(2) call may be used to read the contents of a symbolic link. Symbolic links may span file systems and may refer to directories. Given one or two arguments, ln creates a link to an existing file source_file. If target_file is given, the link has that name; target_file may also be a directory in which to place the link; otherwise it is placed in the cur- rent directory. If only the directory is specified, the link will be made to the last component of source_file. Given more than two arguments, ln makes links in target_dir to all the named source files. The links made will have the same name as the files being linked to.
8 CentOS (useful commands)
systemctl –state=running systemctl –state=running=ru
9 Colour in bash scripts:
9.1 tput
Call tput as part of a sequence of commands:
tput setaf 1; echo "this is red text"
Use ; instead of && so if tput errors, the text still shows.
Another option is to use shell variables:
- red=`tput setaf 1`
- green=`tput setaf 2`
- reset=`tput sgr0`
- echo "${red}red text \({green}green text\){reset}"
tput produces character sequences that are interpreted by the terminal as having a special meaning. They will not be shown themselves. Note that they can still be saved into files or processed as input by programs other than the terminal.
#!/bin/bash RED='\033[0;31m' YELLOW='\033[1;33;40m' NC='\033[0m' # No Color RED=`tput setaf 1` GREEN=`tput setaf 2` YELLOW=`tput setaf 3` BLUE=`tput setaf 4` MAGENTA=`tput setaf 5` CYAN=`tput setaf 6` WHITE=`tput setaf 6` printf "Here is ${RED}red${NC} and here is ${YELLOW}yellow${NC}\n" echo " " echo " Showing what python, python2, and python3 would be running based on" echo " environment variables set as shown: " echo "--------------------------------- " for x in python python2 python3; do echo "${CYAN}"; which $x echo "${YELLOW}"; readlink $(which $x) echo "${MAGENTA}";$x --version echo "-----------------------------------" done echo "" echo " Current values of environment variables:" echo " PATH is $PATH" echo " PYENV_VERSION is $PYENV_VERSION" echo "" echo ""
#!/bin/bash ## brew uninstall --force --ignore-dependencies python python2 python2.7 python3 python3.6 > /dev/null 2>&1 ## brew install python@2 python@3 > /dev/null 2>&1 RED='\033[0;31m' YELLOW='\033[1;33;40m' NC='\033[0m' # No Color RED=`tput setaf 1` GREEN=`tput setaf 2` YELLOW=`tput setaf 3` BLUE=`tput setaf 4` MAGENTA=`tput setaf 5` CYAN=`tput setaf 6` WHITE=`tput setaf 6` printf "I ${RED}love${NC} Stack Overflow\n" echo " " echo " Showing what python, python2, and python3 would be running based on" echo " environment variables set as shown: " echo "--------------------------------- " echo "${CYAN} done" for x in python python2 python3; do which $x readlink $(which $x) $x --version echo "-----------------------------------" done echo "" echo " Current values of environment variables:" echo " PATH is $PATH" echo " PYENV_VERSION is $PYENV_VERSION" echo "" echo "" alias taka='tput setaf 5;echo -e "${PURPLE}${PATH//:/\\n}"'