Basics
https://linuxcommandlibrary.com/
- https://www.howtogeek.com/269509/how-to-run-two-or-more-terminal-commands-at-once-in-linux/
Option One: The Semicolon (;) Operator
The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds. For example, open a Terminal window (Ctrl+Alt+T in Ubuntu and Linux Mint). Then, type the following three commands on one line, separated by semicolons, and press Enter. This will give you a listing of the current directory
Option Two: The Logical AND Operator (&&)
If you want the second command to only run if the first command is successful, separate the commands with the logical AND operator, which is two ampersands ( && ). For example, we want to make a directory called MyFolder and then change to that directory--provided it was successfully created. So, we type the following on the command line and press Enter.
Option Three: The Logical OR Operator (||)
Sometimes you might want to execute a second command only if the first command does not succeed. To do this, we use the logical OR operator, or two vertical bars ( || ). For example, we want to check to see if the MyFolder directory exists ( \[ -d ~/MyFolder \] ) and create it if it doesn't ( mkdir ~/MyFolder ). So, we type the following command at the prompt and press Enter.
- bash cheatsheet
```bash
A; B # Run A and then B, regardless of success of A
A && B # Run B if and only if A succeeded
A || B # Run B if and only if A failed
A & # Run A in background.
A & B & : # Run A in background, then run B in background (regardless of success) and return control to the shell
```
- locating commands or bin files
`which -a gdb`
```
which: no gdb in (/home/hpm/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/var/lib/snapd/snap/bin)
```
rt
`locate -eb '\gdb'`
ed
```bash
/usr/share/gdb
/usr/share/bash-completion/completions/gdb
/usr/share/glib-2.0/gdb
/usr/share/gstreamer-1.0/gdb
```
- sed commands usage
https://www.tecmint.com/linux-sed-command-tips-tricks/
https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/
[Sed Command in Linux_Unix with examples - GeeksforGeeks.pdf](../../_resources/Sed%20Command%20in%20Linux_Unix%20with%20examples%20-%20Geeksfor.pdf)
- List files with full path with ls
`ls -lrt -d -1 "$PWD"/{*,.*}`
or if u want regular expression then
`find /path/to/start/directory -type f | awk -F/ '{print ""$NF""}'`
here path to directory is path where those files are stored
`type -f` means to list only files
`find /path/to/start/directory -maxdepth 1 -type f -exec sh -c 'echo "$(basename {})"' \;` : this maxdepth flag can be used to list files only in current directroy and not go any deeper in those subdirectories
- cp command
to copy folder contents along with hidden files use the period(.) symbol too
`cp -ar assets/. backup/` a is for archive means preserving metadata
to copy files while excluding a file or directory
`rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherFolderToExclude`
Note : files to be excluded should be relative to source directory not the current directory from where this command is executed.
- Changing file name based on pattern
```bash
for file in tomp3.cc*; do mv "$file" "${file/tomp3.cc - /}"
done
```
- replacing names through like removing spaces
`for f in *\ *; do mv "$f" "${f// /_}"; done`
Though it's not recursive, it's quite fast and simple. I'm sure someone here could update it to be recursive.
The `${f// /_}` part utilizes bash's parameter expansion mechanism to replace a pattern within a parameter with supplied string. The relevant syntax is `${parameter/pattern/string}`. See: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html or http://wiki.bash-hackers.org/syntax/pe .
- sort file names
on basis of names
- ascending order
`ls *.jpg | sort -n`
- descending order
`ls *.jpg | sort -nr`
- get ip address
`ip addr` or `ifconfig`
- cat command
1. `cat notes.txt` : to show contents of notes,txt
2. `>` this will represent the transfer of data from left to right. If left side is empty then transfer from stdin to the file. All content of file will be replaced with stdin or whatever file on left.
```bash
cat > notes.txt
> hey there
>^C
> cat notes.txt
> hey there
```
3. `>>` will append data from left to right instead of truncaing it
```bash
cat >> notes.txt
> hey there
>^C
> cat >> notes.txt
> how r you
>^C
> cat notes.txt
> hey there
> how r you
```
- aliases and function
1. Functions
```
function packagelist {
dpkg -l | grep "$1" | awk '{print $2}' | tr "\n" " "
}
packagelist gcc
```
Output:

- Docs
Install tldr package to get nicer docs. or tealdeer which is rust based
- Some utilties info
tty is the terminal device a process is connected to
it can be a physical terminal or a pseudo terminal
`ps` is a command that displays process information
and `tail` prints to output the last contents of a file
by default the last 10 lines
`ps -eo user= | sort | uniq -c`
one-liner counts the number of processes per user on the system
ps -eo user= extracts only usernames with no header line (the '=' clears the custom header, which suppresses the header line entirely), sort arranges them, uniq -c counts processes per user. Without '=', the header row 'USER' itself would be counted as one entry.
- Check memory info
`free -m`
- Check battery status
To list devices
`upower -e`
Find battery one and get the result
`upower -i /org/freedesktop/UPower/devices/battery_BAT0`
- Check desktop manager
`systemctl list-units | grep dm.service`
- Check whether xorg or wayland display server
`echo $XDG_SESSION_TYPE`
- last argument access
For eg if u have used
`mkdir test`
Then `$_` will represent `test`
So
`cd $_` = `cd test`
- for checking CPU architecture use
`uname -m`
- zswap
compresses ram istead of using storage space
- search for packages : pinned
`find /usr -name '*mingw*'`
- script for mounting multiple partitions
```bash
#!/bin/bash
name1="mint"
name2="manjaro"
name3="hdd"
name4="ssd"
# Define partitions and mount points
partition1="/dev/sda5" # mint
partition2="/dev/sda6" # manjaro
partition3="/dev/sda3" # hdd
partition4="/dev/nvme0n1p3" # ssd
mount_point1="/mnt/$name1"
mount_point2="/mnt/$name2"
mount_point3="/mnt/$name3"
mount_point4="/mnt/$name4"
# Check if partitions are not mounted
if ! mountpoint -q "$mount_point1"; then
mkdir -p /mnt/$name1
# Mount partition1
sudo mount "$partition1" "$mount_point1"
echo "Mounted $partition1 at $mount_point1"
fi
if ! mountpoint -q "$mount_point2"; then
mkdir -p /mnt/$name2
# Mount partition2
sudo mount "$partition2" "$mount_point2"
echo "Mounted $partition2 at $mount_point2"
fi
if ! mountpoint -q "$mount_point3"; then
mkdir -p /mnt/$name3
# Mount partition3
sudo mount "$partition3" "$mount_point3"
echo "Mounted $partition3 at $mount_point3"
fi
if ! mountpoint -q "$mount_point4"; then
mkdir -p /mnt/$name4
# Mount partition4
sudo mount "$partition4" "$mount_point4"
echo "Mounted $partition4 at $mount_point4"
fi
```
- size of folders and files
The `du` command in Linux is a powerful utility that allows users to analyze and report on disk usage within directories and files.
The basic syntax of the du command is as follows:
`du [options] [directory/file]`
eg : `du -sh dir_name`
- copy all files to next folder with exlcuding some directories say `src`
`rsync -av --exclude='src' . ~/cache_bkp`
`.` here is source and `~/cache_bkp` is destination
- to prepend text
// this way is working
`echo -e "your text to prepend\n$(cat sample.txt)" > sample.txt`
for large files
```bash
echo "your text to prepend" > temp.txt
cat sample.txt >> temp.txt
mv temp.txt sample.txt
```
// below way isnt working
`cat - stringToBePrepended | tee -a sample.txt.`
cat - reads from standard input (in this case, the stringToBePrepended).
Step 2:
Pipes the output of cat - text.txt to the next command.
Step 3: tee -a sample.txt
tee -a appends the input to the sample.txt file.
The -a option tells tee to append to the file instead of overwriting it.
Overall effect:
The cat - text.txt | tee -a sample.txt command reads the contents of text.txt, appends them to sample.txt, and also outputs them to the terminal. This effectively prepends the contents of text.txt to sample.txt.
Harsh Truth
—
Today at 12:20 AM
- Looping thorugh all arguments in bash
```bash
for arg in "$@"; do
echo "arg: $arg"
done
```
- Detecting flags in bash
```bash
#!/bin/bash
# Loop through all the arguments
for arg in "$@"; do
case $arg in
-a|--optionA)
echo "Option A detected!"
# handle option A
;;
-b|--optionB)
echo "Option B detected!"
# handle option B
;;
*)
# Handle positional arguments or invalid flags
;;
esac
done
```
- sed
`sed -i 's/\(\)\.md/\1/' your_file.txt`
This command captures the `` before .md using parentheses and then replaces the entire match (including .md) with just ``, effectively removing the .md extension when it follows ``.
- Copy multiple files to a directory
`cp -t path/to/destination_directory path/to/file1 path/to/file2 ...`
- Copy multiple directories to a directory(copy `dir1` `dir2` to `targetDir`)
`cp -r dir1 dir2 targetDir/`
- Move multiple directories to directory
`mv -t path/to/destination_directory path/to/file1 path/to/file2 ...`
- Login to different user
`sudo su - ` and `exit` to exit
- User management
https://www.freecodecamp.org/news/how-to-manage-users-in-linux/
- Adding user
`useradd -u 1002 -d /home/john -s /bin/bash john`
or
`useradd -u 1002 -d /home/john -s /bin/bash john -g johnGroup -c comments`
- Getting user names
Users and their other informatio separated by colons can be accessed by
`cat /etc/passwd`
To get only users
`awk -F: '{ print $1}' /etc/passwd`
Get users which can be logined
`getent passwd {1000..60000}`
1000 is min UID and 60000 is max UID. They may be different so find them using
`grep -E '^UID_MIN|^UID_MAX' /etc/login.defs`
following for users with uid and gid
`cut -d: -f1-4 /etc/passwd`
- Getting group names
`cat /etc/group`
or
`cut -d: -f1 /etc/group | sort` (for readable form)
- get group names for a user
`groups $USER`
`id $USER`
- Password setup
After creatiing user before login in we can setup password by
`sudo passwd john`
- Adding permissions
By default when user is created he dont have permission to write anything there so he cant create any directory or file too in his own home directory. Before login in type this
`sudo chown test:test /home/test`
- Adding user to group
https://serverfault.com/questions/688685/usermod-ag-vs-gpasswd-a-as-a-best-practice
`sudo gpasswd -a $USER groupname`
or
`sudo usermod -aG groupname username`
or for adding user to multiple groups
`sudo usermod -aG additional_groups username`
`additional_groups` : comma separated list of groups
- Ensure group changes to take effect
`newgrp group_name`
- Allowing user to use sudo
Uncomment the line starring `$ sudo ...` then
`sudo usermod -aG sudo username` so add user to sudo group
`-aG` means adding user to group
or use
`sudo usermod -aG wheel username` if u dont wanna uncomment sudo and use wheel instead
wheel will grant user priviledge to use sudo command
To remove users from group 'wheel'
`sudo gpasswd -d username wheel`
- Changing ownership
`chown -c john file.txt` (for users)
or
`chown -c :johnGroup file.txt` (for groups)
`-c` for reporting
for directories use
`chown -R -c john file.txt` (for users)
- Running command as different user without login
`su - username -c 'command'`
or
`sudo -u username command`
- Granting permissions
to all root access priviledges to the user then
add this to sudoers file (location : /etc/sudoers)
`username ALL=(ALL:ALL) ALL` (very dangerous config so avoid it as much as possible as it will grant nlimited access too)
when installing distro first user can use cd or ls command in directories without use of sudo so do this
`sudo usermod -aG autologin $USER` to add ability as same of first user
if it doesnt work then check permissions and using chmod change
- Extended partition. access grant of directory can be `drwxr-x--x+` here `+` at end stands for extended permissions means other user cant access its directories even if is set `x` permission in others. Extended permissions is honored by fish shell but not bash shell may not honor it. to change it use `setfactl` and to get its detail use `getfactl`
To add extended permissions use
`setfacl -R u:user2:wrx /tmp`
to remove
`setfacl -bn /tmp`
- to check permissions of directory simply instead of all files in it use `ls -ld `
- For searching files
`find /home/user/ | grep filenamehere`
- launch other user files with this
`sudo -e /path/to/other/users/binary`
`-e` preserves your current user's environment variables etc. so audio should work
- change to new user
`sudo su - test`
- for searching files with particular extension also listing their meta data
`find . -type f -name "*.ess" -exec ls -l {} +`
- for searching with min length 1 mb
`find -size +1M`
- scrolling in terminal
TIL that u can scroll in terminal with `SHIFT+PGUP/PGDOWN`
- useful commands
to count number of files in current directory
```sh
ls | wc -l
```
- tar and cpio
cpio
```bash
# creating archive of text files to archive.cpio
find *.txt | cpio -o > archive.cpio
# extracting content to current directory
cpio -i < ../archive.cpio
```
- to search for content recurseively across all files in a directory
`grep -r hello `
- resources, basic command video
https://youtu.be/QhvDvpyvPSE
```txt
Nick, tell the beginners use 'trash' instead of 'delete, to retain file availability.
Nick, tell the beginners that 'pwd' is NOT password.
Nick, tell the beginners that 'cd -' takes them between recent directories.
Nick, tell the beginners that Windows says 'folders', but Linux says 'directories'.
Nick, tell the beginners that uppercase and lowercase letters denote DIFFERENT things in Linux.
```
- `arp -a` to get list of all otheer ip address of systems connected to same network
- find number of files and directories recursively in given directory
`find . -type f | wc -l` for files
`find . -type d | wc -l` for directories
- to identify distro u r using
`cat /etc/os-release `
- to see disk space left for each partitions
`df -h`
for resumable downloads use `-c` in wget
`wget -c https://example.com`