Study

The Most Popular Linux & Terminal Commands

See the tutorial on “WSL Tutorial and Basic Linux commands” first:


Notes taken from:


Table of Contents:


For reference: A table listing some popular Linux distributions along with their associated operating systems and the package managers they use:

Distribution Associated Operating Systems Package Manager Possible Desktop Environments
Red Hat CentOS, Fedora, Oracle Linux, Rocky Linux RPM GNOME, KDE, Xfce, Cinnamon, LXQt
Debian Ubuntu, Linux Mint, KDE neon, Zorin OS, Kali Linux, Pop! OS, MX Linux, Elementary OS, Raspberry Pi OS APT GNOME, KDE, Xfce, Cinnamon, LXQt, MATE
Arch Linux Manjaro, Antergos, EndeavourOS, ArcoLinux Pacman GNOME, KDE, Xfce, Cinnamon, LXQt
SUSE Linux openSUSE, SUSE Linux Enterprise Server Zypper GNOME, KDE, Xfce, LXQt
Slackware Absolute Linux, Zenwalk Linux, Slax pkgtools Xfce, Fluxbox, KDE, MATE
Gentoo Sabayon, Funtoo, Calculate Linux Portage GNOME, KDE, Xfce, LXQt, MATE
Alpine Linux postmarketOS, Adélie Linux, NixOS APK XFCE, i3, Fluxbox, MATE
Mageia OpenMandriva, PCLinuxOS, ROSA Linux urpmi GNOME, KDE, Xfce, LXQt
Solus Budgie, GNOME, MATE, Plasma eopkg Budgie, GNOME, MATE, Plasma
Void Linux Artix Linux, Obarun, Adélie Linux XBPS Xfce, Cinnamon, Enlightenment, MATE
macOS - Homebrew Aqua (default)

Note: macOS is a proprietary operating system (is not a Linux distribution) developed by Apple and differs significantly from Linux distributions in terms of its core architecture and package management.


Bash Shortcuts

Most used shortcuts in bash (More here):

Bash Control/Processes


Bash Manual

Each argument given to man command is normaly the name of the program, utility or function, then the information/documentation about that is displayed.

man man
man bash
man <command>
man git
man gcc
man python3

An alternative to man is tldr (as in “too long didn’t read”) command, that only lists some direct/command examples of using the specified command:

sudo apt install tldr


Basic Linux Commands

touch, echo, cat, head, tail, less

Create files with touch - Note that touch is mainly used to alter the “modified” timestamp of a file:

touch myfile.txt

# You can create multiple files
nano file1.txt markdownFile.md script.py

(More on Nano here: The 50 Most Popular Linux & Terminal Commands - 3h23m48s)

You can create and edit files with nano editor (after entering nano editor, you will have multiple options like “save” CTRL+O, or “exit” CTRL+X):

nano hello.py

You can also create a file with content already in it by using echo "your_string" and direct the content to the file using > operator (redirect standard output):

echo "This is my text file" > myfile.txt
echo "print("hi there")" > hi.py
python3 hi.py

You can also add content to the bottom of a file that already has content in it (append more content to end of file) by using >> operator. Note: you can also view the content of a file using cat file.txt

echo "My first text line" > myfile.txt
echo "My second text line on the same file" >> myfile.txt
cat myfile.txt

# will output
# My first text line
# My second text line on the same file
# Concatenate multiple files with cat
cat butcher.txt groceries.txt > shoppingList.txt

# Show line numbers with cat
cat -n pythonScript.py
date
# will print Tue 10 May 2022, 21:44:47 +0300

date > today.txt

Both > and >> operators create a file if the mentioned file is not existent in current folder (https://linuxhint.com/difference-arrow-double-arrow-bash/), and:


Note: You can see the content of a file by using cat. Or, you can see the first 10 lines of a files by running head command (head myfile.txt), and if you want to see the last 10 lines from a file, run tail (tail myfile.txt). There are also more and less commands in order to see the content of a file “page by page” (more myfile.txt) or line by line (less myfile.txt).

# Show the first 100 lines of a file
head song_lyrics.txt -n 100

# Show the last 50 lines of a file
tail scripts.sh -n 50

With less command, we also find strings by writing /mysearchedstring while we have a file opened:

less myfile.txt
# press / and search your string



You can also use other text editor like gedit, or vim (that is almost used as an IDE) - you can run vimtutor command for a complete vim editor walkthrough.

vim myfile.txt

With touch (man touch for manual) we can manipulate the “modified” timestamp of files. Here we can mention the timestamp in any way we want, even as “2 hours ago” (with -d flag).

touch -d "09:00" myfile.txt
touch -d "2 hours ago" myfile.txt
touch -d "2022-02-24 13:23:40" myfile.txt
touch -d "next Wednesday" myfile.txt
touch -d "last Monday" myfile.txt
touch -d "last Thursday 16:21:32" myfile.txt
touch -d "Sun, 29 Feb 2020 16:21:42" myfile.txt
touch -d '1 June 2018 11:02' file1

# you can also touch multiple files
touch myfile1.txt myfile2.txt myfile3.txt


mkdir, rmdir, rm

mkdir myfolder
rmdir myfolder
rm -r myfolder
mkdir -p mydir/mysubdir
cd mydir/mysubdir
rm -r myfolder
rm file1.txt file2.txt file3.md
rm *.jpg


split

Split large (text) files into smaller files (default is 1000 lines per file). This is useful when we have a huge log file (that contains millions of lines of logs) and we want it to be split in several files that contains around 100,000 (or 200,000) lines in order to be opened by a text editor without freezing our PC (eg. with Notepad++ we can make operations such as highlighting and complex searching).

The base syntax is: split [options] <name_of_file> <prefix_for_new_files>.

split -l 2000 ./logfile.log logfile_

split -l 2000 ./logfile.log logfile_ --additional-sufix=".log"

# and if you want to delete the created files after
rm logfile_*.log

split -l 10000 ./logfile.log log_ --additional-suffix=".log" -d

# Optionally, move the new subfiles into a new folder
mkdir logsplit
mv log_*.log ./logsplit
cd ./logsplit

# And now you can grep through them and open only
# the file of interest that matched your string pattern
grep -rnia ./ -e "ERROR_NAME"

🟢 Note, if you want to split by file size (each separate file will have a defined file size in KB or MB), we use -b (bytes) option instead of -l (lines):

# This will output 100KB files
split -b 100k ./logfile.log log_ --additional-suffix=".log" -d

# This will output 100MB files
split -b 100m ./logfile.log log_ --additional-suffix=".log" -d


ls, cd, open

pwd
ls
ls ./myfolder/mysubfolder
ls /pathFromRoot/to/folder

ls -lah

ls flags:

For example, to sort files by size within a folder, run ls --sort=size -lah (“sort by size”).

Note: Instead of using ls -la, you can directly write ll (double “L”) for the same effect. For human readable sizes, use you can ll -h instead of ls -lah. ll is a predefined alias for ls -alF (at least on Ubuntu/Mint/Zorin/other derivates).

ll

# sames as
ls -la
type ll
# ll is aliased to `ls -alF'

You can edit (permanently) this alias further to ls -alFh (for human-readable). Just search and modify the alias in the ~/.bashrc file (bash script that is executed every time the system boots).

nano ~/.bashrc

# press CTRL+W to search for "alias ll"


cd mydir/myotherdir
cd ..
cd ../..


xdg-open filename.txt
xdg-open folder_name

# open current directory in Finder/Dolphin/File explorer etc
xdg-open .


mv, cp

(Tuesday, 10 May 2022)

mv hi.py ../hi.py  # move one folder up
mv ../hi.py ./hi.py  # move file from one folder up to current folder/path

# You can also move multiple files (ex. within a directory)
mv file1 file2 file3 DestFolder/


mv currentFileName.txt newFileName.txt
mv hi.py hello.py


cp file_2.txt file_3.txt
cp hello.py ../hello2.py

# to copy a folder that has files in it
cp -r folder folder_copy

# If folder does not exist
cp hello.py /v2/hello.py  # cp: cannot create regular file '/v2/hello2.py': No such file or directory
mkdir -p ./v2 && cp hello.py $_

https://stackoverflow.com/questions/1529946/linux-copy-and-create-destination-dir-if-it-does-not-exist

Copy all .txt files from a folder into another foder:

mkdir ./random/texts_folder
cp -rv ./random/*.txt ./random/texts_folder


Also, cp is often used for backups

cp file_2.txt{,.bkp}

cp hello.py{,.bkp}
cp hello.py hello.py.bkp #  the equivalent command


wc

wc LongTextFiles.txt
# 1757 15767 87022
# lines words bytes
echo -e "cat\ndog\nmouse\nrabbit\nfish" | wc -l
# 5 lines

Note: The echo -e option enables interpretion of backslash, meaning /n will tell echo to write each string to a new line.


Linux File System


From:


Piping commands

We can take the output of a command, and pass it as an input to another command. Examples:

echo "How many words are here" | wc
# 1 line, 5 words, 24 bytes

echo "Hello" > greeting.txt
echo "How are you?" >> greeting.txt
wc -l greeting.txt
# 2 lines
ls | wc -l

ls /etc | echo "There are $(wc -l) files"

# include/count hidden files as well
ls -a | wc -l
cat appliances.txt groceris.txt | wc -l

cat server1.log server2.log server3.log | wc -l


Expansions

Note that in Linux, some strings are interpreted as other strings (just like aliases or hotstrings). For example, whenever we write ~ it is expanded to /home/username path.

echo ~
# will print /home/username

We can also see some popular Environment Variables (variables in bash start with $).

Another example is *, that is an expansion to every filename in current directory (pwd). And, we can also narrow down to *.txt (shows every filename that matches with .txt at end). Other use-case of using * alias, is listing all files that ends with an extension: ls -lah *.txt.

echo $USER
echo $SHELL
echo $PATH


Another useful alias is ? (question mark), that matches every single character. Two ?? will match two any-characters in a row, three ??? will match 3 characters and so on.

# example: match any filename that ends with an extension of exactly 2 characters
ls -lah *.??


Another extension is use of curly braces {}, where bash will expand to the values within curly braces (separated by , comma).

echo {a,b,c}.txt
# a.txt b.txt c.txt

echo a{d,c,b}e
# ade ace abe

touch app.{html,css,js,py}
# will create 4 files: app.html app.css app.js app.py
ls app.*
# app.css app.html app.js app.py

We can also expand into ranges, like {1..10}, or {a..z}.

echo {1..10}
# 1 2 3 4 5 6 7 8 9 10

echo file{01..05}.txt
# file01.txt file02.txt file03.txt file04.txt file05.txt

touch file{01..10}.txt
# will create 10 files
echo {Z..A}
# Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

More on expansions here: https://linuxcommand.org/lc3_lts0080.php


Searching, Sorting, Replacing

sort

The 50 Most Popular Linux Commands - 1h56min

sort file.txt

sort file.txt > file_sorted_lines.txt

sort -n nums.

sort -nur nums.txt # -r option to sort in reverse order

More on sort here: https://www.geeksforgeeks.org/sort-command-linuxunix-examples/

cat logsWithTimestamps01.log logsWithTimestamps02.log | sort

cat logsWithTimestamps01.log logsWithTimestamps02.log | sort > allLogsSorted.log
sort -gk 2 shopping.txt

sort -nrk 3 employees.txt

See more about sorting floating point numbers (general sorting) here: https://unix.stackexchange.com/questions/459257/how-to-sort-lines-by-float-number.


uniq

If we have a text files that has duplicated lines, we can use uniq to print out the content of that file without adjacent duplicates lines (consecutive duplicated lines one after another):

uniq logs.log

If we want to remove all duplicated lines, we can use uniq in combination with sort:

sort langs.txt | uniq

# this is same as running sort -u langs.txt
sort -u langs.txt

However, if we only want to show us the dupliacated in a file, we can run sort langs.txt | uniq -d. And if we want only the lines that appear once (non-duplicates), we can run sort langs.txt | uniq -u.

And, if we want to count how many times each line is repeating, we can use the count option: sort langs.txt | uniq -c. And we can even sort that numerically:

sort flavours.txt | uniq -c | sort -n


find

The Most Popular Linux Commands: find - 2h21m

To find files in the entire system (/ - the root directory) or in current path (.) and folders inside (recursively), we can use find (man find) - it will output the path(s) to the searched file:

find path_name

find / -name "host.conf"
find . -name "docker-compose.yml"
# show all .py files in current path and folders inside (recursively)
find . -name "*.py"  # same as ls *.py

# find a file that has the exact math of "myfile.txt"
find /path/to/a/folder -name "myfile.txt"

# find by type
find . -type d  # eg find all directories (d)
find . -type f  # find only files, not directories
find . -type d -name '*new*'  # find all directories that contain 'new' in their name
find . -type d -iname '*new*'  # find all directories that contain 'new' or 'New' in their name
# eg Find directories under the current tree matching name "node_modules" or "public"
find . -type d -name "node_modules" -or -name "public"
find . -name "*.md" -not -path "node_modules"

More examples:

find . -type f -size +100c
find . -type f -size +100k -size -2M
find . -type f -mtime +3
find . -type f -mtime -1


With the found files, youn can run another command on them with -exec (just like piping, however piping is not supported with find command, you can’t run something like find -name "F*.txt" | ls -lah, but instead you can run find -name "F*.txt" -exec ls -lah \;). Note that every command after -exec should end with \;

find . -type f -mtime -1 -exec ls -lah {} \;
find . -name "*.py" -exec cat {} \;  # {} will be replaced with "file1.py file2.py" etc


ack

To search for strings inside files (and output their path), use ack (man ack), is just as powerful, but easier than grep. Note, it is possible that ack needs to be installed (sudo apt install ack for Debian based distros).

ack -i 'stringpattern'

# or grep equivalent
grep -rni '/path/to/somewhere/' -e 'stringpattern'
# -r or -R is recursive
# -n is to show line number in file
# -w stands for match the whole word
# -l (lower-case L) can be added to just give the file name of matching files (show the file name, not the result itself)
# -e is the pattern used during the search
# -i for ignore case

https://stackoverflow.com/questions/16956810/how-do-i-find-all-files-containing-specific-text-on-linux


grep

(Sunday, May 22, 2022)

The Most Popular Linux Commands: grep - 2h32m

grep (global regular expression print) is used to search for text inside files.

grep -n Sarah employees.txt

# see some Context related to found words (eg show 2 before and 2 lines after)
grep -nc 2 Sarah employees.txt
grep -ri "hello"


To use regular expressions in grep, we need to use -E flag (“Extended regular expressions”, by default it’s using -G for basic regex)

# Search by emails in all files in current directory
grep -rE -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" .


Some other random examples of using grep:

history | grep "sudo apt install" > installed_apps.txt

# or if you want to save to a file without line numbers
history -w history.txt
grep "sudo apt install" history.txt > history.txt


grep -rnia ./app_logs -e "Request failed"


# get the lines that contains "OutOfMemoryError" string
grep -rnia ./ -e "OutOfMemoryError"

# show the 4 lines before every line that contains "OutOfMemoryError" string
grep -B 4 -rnia ./ -e "OutOfMemoryError"

# show the 4 lines that comes after every line that contains "OutOfMemoryError" string
grep -A 4 -rnia ./ -e "OutOfMemoryError"


pdfgrep

Search text within multiple pdfs and docs - askubuntu.com

sudo apt install pdfgrep

Search text within multiple PDFs by using pdfgrep -r "my expression" where -r searches recursively through directories.

# Example
pdfgrep -B 4 -A 4 -rnia ./ -e "storage.*limitation"


sed

(Monday, April 17, 2023)

SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. However, most common use of SED command is for substitution or for find and replace. Syntax: sed OPTIONS... [SCRIPT] [INPUTFILE...]

Example: sed 's/unix/linux/g' sedExample.txt, where:

cat sedExample.txt
# Unix is great OS. unix is opensource. unix is a free os.
# Operating Unix is a great skill to know in 2023

sed 's/unix/linux/g' sedExample.txt
# Unix is great OS. linux is opensource. linux is a free os.
# Operating Unix is a great skill to know in 2023

# ^^ Note that the above command was case sensitive and "Unix" was not replaced


Another example: Parenthesize first character of each word:

echo "Welcome aboard, Captain!" | sed 's/\(\b[A-Z]\)/\(\1\)/gi'
# (W)elcome (a)board, (C)aptain!


Another more complex example:

sed -i s/${bamboo.POM_LEAD_VERSION}.${bamboo.POM_VERSION}/${bamboo.releaseBuildNumber}/g ./pom.xml

Let’s say the value of bamboo.POM_LEAD_VERSION is “1.0” and the value of bamboo.POM_VERSION is “SNAPSHOT” and the value of bamboo.releaseBuildNumber is “12”. The pom.xml file contains the following line:

<version>1.0.SNAPSHOT</version>

After running the sed command you provided, the pom.xml file will be modified in place, and the line will be changed to:

<version>12</version>


Some of the above notes for sed command were taken from:


Disk usage commands

du

du -h .  # will show all the sizes of directories within current path tree
du -ah .
du -sh /*
du -ah | sort -h

# we can also use
ls --sort=size -lahr

# and if we want top 5 largest files
ls --sort=size -lahr | tail -n 5

# or top 10 largest files using du (and reversing the list)
du -ah | sort -hr | head


df

df -h

# or

df -h /

See the disk usage of the filesystem (like a “partition” but not really) where ~/Desktop is located

df -h ~/Desktop

# will prind something like
# Filesystem      Size  Used Avail Use% Mounted on
# /dev/sda5       439G   39G  378G  10% /


history

(Monday, May 23, 2022)

The Most Popular Linux Commands: history - 2h44m

The history command shows a list of the commands entered since you started the session. You can replay any command from history by using a command such as: !3 (with exclamation mark and history id from history list, like !command_id_from_history)

history
history | less

!145 # runs command 145 from history list

You can also search through history by piping grep:

# See all apt installs
history | grep "sudo apt install"

# See all commits made
history | grep "git commit"

# View compiled C files with gcc or ran/interpreted with Python3
history | grep "gcc"
history | grep "python3"

# View all .txt files edited in vim (or nano)
history | grep -E "vim.*txt"


CTRL+R shortcut

However, another way to get to this search functionality is by typing Ctrl+R to invoke a recursive search of your command history. After typing this, the prompt changes to:

(reverse-i-search)`':

Now you can start typing a command, and matching commands will be displayed for you to execute by pressing Return or Enter, or keep pressing CTRL+R until you find the match you want.


Erasing history

From https://opensource.com/article/18/6/history-command: If you want to delete a particular command, enter history -d <line number>. To clear the entire contents of the history file, execute history -c.

The history file is stored in a file that you can modify, as well. Bash shell users find it in their home directory as .bash_history.

nano ~/.bash_history


See history commands with timestamps

Solution taken from: https://askubuntu.com/questions/391082/how-to-see-time-stamps-in-bash-history

# for e.g. “1999-02-29 23:59:59”
HISTTIMEFORMAT="%F %T "

# for e.g. “29/02/99 23:59:59”
HISTTIMEFORMAT="%d/%m/%y %T "
echo 'HISTTIMEFORMAT="%F %T "' >> ~/.bashrc
source ~/.bashrc

Note that this will only record timestamps for new history items, after HISTTIMEFORMAT is set for sessions, i.e. you can’t use this retrospectively.


Processes

ps, htop

The Most Popular Linux Commands: ps - 2h47m

You can inspect processes (started by current user/you) that running on your Linux machine with ps.

To see all the processes by all users run ps ax (or, to see all the processes in a GUI you can run top and htop). To view all the path related to processes you can run ps axww (with simple ps ax the names gets cut, by adding ww word-wrap we can see the entire path).

ps axww


However, a waaay easier method to manage processes is by installing and using htop. See The htop Command | Linux Essentials Tutorial

htop


kill

Notes taken from the book: https://www.freecodecamp.org/news/the-linux-commands-handbook/#the-linux-kill-command

kill <PID>

By default, this sends the TERM signal to the process id specified.

We can use flags to send other signals (Note that we can view all the flags by running kill -l that won’t kill anything, it will just list all the signals we can use)

kill -HUP <PID>
kill -INT <PID>
kill -KILL <PID>
kill -TERM <PID>
kill -CONT <PID>
kill -STOP <PID>


killall

https://www.freecodecamp.org/news/the-linux-commands-handbook/#the-linux-killall-command

Similar to the kill command, killall will send the signal to multiple processes with same name at once instead of sending a signal to a specific process id.

killall <name>

where name is the name of a program. For example you can have multiple instances of the top program running, and killall top will terminate them all.


jobs, bg, fg

The Most Popular Linux Commands: jobs, bg, fg - 2h47m

We can put (long) running commands in the background in our terminal, so we can run other commands.

For example, if we run a command that takes a lot of time (eg. grep -rnia ./huge-logs.log -e "stringpattern" or find / -ctime -1 to find all files in root directory that changed in the last 24 hours), the command will run in the foreground, where we can either:

Note: we can also run a process (a command) directly in the background by adding ` & at the end of the command (for example grep -rna ./logs.log -e “timestamp” > logs-today.log &, or something like docker-compose up &`).

Note: we can also suspend (CTRL+Z) “processes” like editing a file in nano/vim -> while we are in nano/vim, press ctrl+z, do something else in the terminal, then run fg command to get back to editing a file in nano/vim (this is especially useful on servers while remote with ssh). This is like “minizing” a program/app (or note-taking with vim/nano) in the terminal.


gzip, tar

(Monday, July 18, 2022)

Gzip is a lossless compression tool that makes large chunks of data smaller (gzip file compression in 100 Seconds - Fireship.io).

gzip --version

# Compress a file
gzip filename.txt  # it will create a filename.txt.gz

# Print the compression rate of gzip file
gzip -l filename.txt.gz
# Decompress gz file to original using -d (Method 1)
gzip -d filename.txt.gz

# Decompress gz file to original using g-unzip (Method 2)
gunzip filename.txt.gz

Note: gzip filename.txt will add filename.txt to the filename.txt.gz compressed file and will delete the filename.txt file. To keep both filename.txt and compressed filename.txt.gz file, add the -k (keep the original) flag: gzip -k filename.txt.

gzip -kv changes.txt # -v for verbose
# changes.txt 86.8% - created changes.txt.gz


However, gzip cannot compress a whole directory. We need to use the tar (tape archive) archiver, with -z flag that compresses multiple files into a single .tar.gz (compressespressed tarball) file.

tar -czvf MyArchiveName.tar.gz MyDirectoryName
# -c flag is for create
# -f flag is for providing the filename the tar will have
# -z flag automatically compresses the archive
# -v flag is for verbose

To extract files from a tar archive we use the -x option (extract):

# Archive without compression
tar -cf MyArchiveName.tar

# View files inside archive with -t option
tar -tf MyArchiveName.tar

# Extract (in the same directory)
tar -xf MyArchiveName.tar

# Extract (in the specified directory)
tar -xf MyArchiveName.tar -C ./extracted

If we want to add multiple selected files into a tar archive:

tar -cfv MyArchiveName.tar file1.log file2.log file3.log

gzip -v MyArchiveName.tar

Note that tar command does not compress any files, so every time we create a tar archive of a group of file, we then need to compress the tar file with gzip. Or we should use the tar -z option (for automatic compress) as shown:

# Archive and Compress files
tar -czvf MyArchiveName.tar.gz file1 file2 file3

# Decompress and extract files from archive
tar -xf MyArchiveName.tar.gz


wget

Wget command is the non-interactive network downloader which is used to download files from the server even when the user has not logged on to the system and it can work in the background without hindering the current process. Syntax: wget [option] [URL]

Examples:

  1. To simply a webpage: wget http://example.com/sample.php

  2. To download the file in background: wget -b http://www.example.com/samplepage.php

  3. To overwrite the log while of the wget command: wget http://www.example.com/filename.txt -o /path/filename.txt

  4. To resume a partially downloaded file: wget -c http://example.com/samplefile.tar.gz


Notes from: https://www.geeksforgeeks.org/wget-command-in-linux-unix/.


xargs

(The Most Popular Linux Commands - xargs 3h43m18s and The Linux xargs command)

(Tuesday, July 19, 2022)

The xargs command is to convert input from standard input into arguments to a command. The syntax for xargs is something like command1 | xargs command2.

Examples:

cat FilesToDelete.txt | xargs rm

We can also add a -p option to print a confirmation prompt with the action performed.


cat FilesToCreate.txt | xargs touch


# Show detalied list of files that are larger than 10MB
find . -size +10M | xargs ls -lh

# And remove those files that are larger than 10MB
find . -size +10M | xargs rm


git ls-files | xargs wc -l

# You can also add more instructions, e.g. looking at the JavaScript files
git ls-files | grep '\.html' | xargs wc -l
git ls-files | grep '\.js' | xargs wc -l
git ls-files | grep '\.ts' | xargs wc -l
git ls-files | grep '\.java' | xargs wc -l


xargs multiple commands

You can also run multiple commands at once using the -I option, that allows you to get the output into a % placeholder.

command1 | xargs -I % /bin/bash -c 'command2 %; command3 %'
# Example
cat FilesToDelete.txt | xargs -I % /bin/bash -c 'cat %; rm %'

# or you can use "sh -c" instead of "/bin/bash -c"
cat FilesToDelete.txt | xargs -I % sh -c 'cat %; rm %'

Note: You can swap the % symbol used above with anything else – it’s a variable.


More xargs examples

ls *.jpg | xargs tar -czvf myjpgs.tar.gz

# and remove them after
rm *jpg


find . -name '*.c' | xargs grep 'stdlib.h'


# Simple example
ls | xargs

cat ListOfItems.txt | xargs


grep -lir 'btn-green, btn-red' ./* | xargs mv -t ./tmp
grep -li 'img' ./* | xargs mv -t ./tmp_imgs


find . -name *.backup -print0 | xargs -0 rm -v


Permissions

Top Linux Commands: permissions - 4h32m


chmod

Examples:


Note: You can also use octals to set permissions to all three groups of users in one command:


Making a bash script executable