Linux Commands
A rough overview of common commands needed for your average Linux user.
CMD Commands
pwd
: To display current working directoryls
: List directories- -a : Show hidden files too
- -l : Show long format filenames shows group,links and al
- -b is block
- -l is symbolic link
- -s is process file
ps
: Display shell runninguname
: Display OS info. Not much to be honest, just gave “Linux”Ctrl + L
: scroll to clean terminalman
: Manual for everythingcd ..
: Root directorycd.
: parent directorycd-
: Go back to last directory very useful
File System Heirarchy
This is just the usual file system you are used to swapnil.
A hypervisor is a software that creates and runs virtual machines and allows running multiple operating systems concurrently, while sharing hardware resources.
Directories like root
, bin
, boot
. dev
, lib
, user
, etc
, usr
, tmp
and the sort.
sda devices are block readable devices, typically 1KB blocks.
Basic System commands
- cal jul 2002 : show calender of that month
- ncal : Same calender,different orientation
- free command for memory
- chmod g-w {foldername} : remove write permisson for group
- chmod 700 {foldernaem} : Numerical method of setting
- touch : create a file/ alter the timestamp
- mv {file1} .. : move one level up
- mv {file1} {newname} : rename file as file2
- mv *txt folder_name : Move all text files into subfolder with name folder_name
- cp {file1} {file2}
- rm : remove file
rm ./file_to_delete.txt
- whoami
alias rm="rm -i"
:set alias for certain commands- znew : shows file type
- file : shows path and all for symbolic links
Parent of root folder is the root folder. i.e, // = /
whatis
: gives a oneliner description about any command extremely awesome
ls and its attributes :
- i(node): shows inode number
- l(ong format) : long format
- d(irectory) : dont enter the directory
To view contents of files these are the methods you can use:
- less : inspect contents:
- wc : show (lines) (words) (bytes on disk)
- head : show first 10 lines
- tail : show last 10 lines
- cat : cat filename : dumps file on the screen
- more : just dumps contents on screen
Informative commands
- man : Show me the manual
- which :
- apropos : search for a keyword (equivalent to man -k)
- info : shows keywords,but this time can click and go to its definition
- whatis
- help : shows keywords reserved by bash environment
- type : shows location of the command in the file system
- cp :
cp file mydir
: copy file from current directory into mydir (non recursive) - ln -s:
ln -s file1 file2
: create soft symbolic llink for file1 in file2(inode nos different) - ln :
ln file1 file3
: create hard link for file1 into file2(inode nos same) - stat : all details about the file
- du : just the size of the file in KB
/proc is a very interesting directory. There are directores with size0 and have content while the others show 140TB sizes and dont even exist. Get all USB devices and drivers here
SHELL VARIABLES
echo
prints onto the screen . All shell variables start with a $.
Frequently used shell variables include:
- $HOME
- $USERNAME
- $HOSTNAME
- $PWD
- $PATH : printenv , setenv,
- $0 : Gives the name of the shell
- $ : Gives process ID
- $? : Returns code of previously run program
- $- : Flag in the bash shell ’ ’ prints verbatim while " " substitutes the values
- export x : export variable x from shell to environment
Process control
- & to run a process in the background
- fg :
- coproc :
- jobs :
- top :
- kill :
- ps : show running processes –forest -e(for everything)
Flags in Bash
- h : locate and hash commands
- B :brace expansion enabled
- i : interactive mode
- s : commands read from stdin
- c : commands read from arguments
- H : rerun command run slightly in the past
- echo $0 : returns the name of the shell being used
- echo $- : type of shell
- echo $? : return of previously executed command
Job Control
sleep x
: sleep for x secondssleep 60 &
: run the sleep in the backgroundcoproc
: Run a coprocess in the background asynchronously- **
kill -9 processid
: Kill the process fg
: Bring the command in the background into the foregroundjobs
: List all the commands running in the backgroundtop
: all processes- bash -d “echo $-” To launh child bash shell without interactive mode hBc (normal is himBhs)
- command ; command ; exit X : run the commands and return with exit code x
history
: list all commands run over past week or so!Number
: run the nth command Multiple commands on the same line can be done using semicolon
bc is bench calculator
file * > filetypes.txt : puts filename and filetype int one file
ln file1 file2 : An excellent use case is when you need to have a synced copy/backup of file1 and file2 is the backup copy which will always remain in sync.
cd (type of file) ../ : moves it up a freaking directory
echo file_{a..z}{a..z}{0..4}.txt > documents.txt : combinations of filenames thing
for i in *.jpg; do convert $i ${i%jpg}png; done
cmd 1 ; cmd2 ; cmd3 : commands executed one after the other
(cmd1 ; cmd2; cmd3) : commands executed parallely in subshells
($BASH_SUBSHELL) : returns 1
(($BASH_SUBSHELL);) : returns 2
Commands :
>
: redirect output to a file.overwrites
cat > file1
: redirect output from command line to a file exit using Ctrl+D
Three file pointers : stdin stdout stderr
ls home >file1 2>&1
:Write both normal contents and error to a file
command1 | command2
: (pipe command) : output of cmd1 goes as input of command2
redirect to 2>/dev/null
will safly dispose off the errrors
|tee
: redirect output to file as well as stdout
ls -l | tee file1
diff file1 file2
: Compare two different files
SHELL VARIABLES:
- Creation :
myvar = value
ORmyvar = " command"
- Exporting :
export myvar = value
ORmyvar = value ; export myvar
- Braces :
${myvar}
- Remove:
unset myvar
ORmyvar =
- Test if a variable is set:
[[ -v myvar]]; echo $?
(0 success)
- Test if a variable is not set:
[[-z ${myvar + x}]]; echo $?
(where x is some random string) (0 variable not set)
- Set a default value if variable is not set else display the value:
echo ${myvar :-"default"}
echo ${myvar :?"default"}
- Set a default value if variable is not set else display the value:
echo ${myvar :+"default"}
- Set a default value if variable is not set else display the value:
- Set a value if a variable is set, else display null:
echo ${myvar :+"default"
: set value of variable to default if it is already set else display null
- echo ${!H*} :
- Display all variables starting with H
- echo ${#myvar}
- Display the length of the variable
- echo ${myvar : 5:4}
- Display a slice of the string from position 5 of length 4
- echo ${myvar #pattern} : Remove matching pattern
- echo ${myvar %pattern} : Display only matching pattern
- echo ${myvar /pattern/string} : Replace the pattern with the string
- echo ${myvar //e/E} : replace every small e with E
- echo ${myvar /#E/e} : replace E only if it occurs at the start of the string
- echo ${myvar /%g/G} : replace g only if it occurs at the end of the string
- echo ${myvar ,} : change first character to lowercase
- echo ${myvar ,,} : change the whole string to lowercase
- echo ${myvar ^} : change the first char to uppercase
- echo ${myvar ^^} : change all the chars to uppercase
declare -flag myvar
:where flag is -i(int) -l(lower) -u(upper) -r(read only)declare +flag myvar
:where flag is +i(int) +l(lower) +u(upper) date +"%d %B"
ARRAYS
- declare -a arr
- $arr[0]=“value”
- echo ${arr[0]} : value of element with index zero
- echo ${#arr[@]} : number of elements in the array
- echo ${ !arr[@]} : Display all indices used
- echo ${arr[@]} : Display all elements in the array
- unset
arr[i]
: Unset the ith element in the array - arr += (“value”) : Append an element to the array at the end
ASSOCIATIVE ARRAY
declare -A arr : array with indexes that can be strings
myfiles=(ls
) :store op of that command in an array
Software Management
fortune -o is fun ;) apt-cache pkgnames “starting letters” md5sum file1.txt : givesthe md5sum hash sha256sum file1.txt: sha1sum
DPKG management Files exist at : /var/lib/dpkg/
dpkg -l pattern :list packages matching the pattern dpkg -L pattern : list file that came from this package dpkg -s package : reprt status of the package dpkg -S pattern : search installed packages for a filedpkg
grep and REGEX
POSIX : Portable OS Interface X means nothing
\(hello\).*\1
.
is any number of any characters
cat names.txt |grep '\(a\).*\1' : matches string with a..stuffinbetween..a
egrep is needed for the regex most people are used to though.
egrep (sa|Sw)
[[:alpha:]] [[alnum]] [[digit]] [[ctrl]] [[punct]] [[space]]
[[graph]] : non control
Negation is using grep -v , the ^ thing doesnt work for this
print empty lines : egrep -v ‘^$’
cut : cut vertically by char
cut -c 1-8 textfile.txt
cut -d " " -f 1
: delimit by space, print first half
PPA :
- Print files where others can rwx
ls -l |egrep 'd[rwx-]{3}[rwx-]{3}rwx' | cut -d " " -f 12
3.Print all files without gnu or GNU
cat test.txt|grep -vi 'gnu'
4. Regex to store files which dont follow lowercase and uppercase
lower=(
ls|grep -v ‘[A-Z]’); upper=(
ls|grep ‘[A-Z]’);