🖥️for
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the for command with important options and switches using examples.
35 minute read
▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁
# ███████╗ ██████╗ ██████╗
# ██╔════╝██╔═══██╗██╔══██╗
# █████╗ ██║ ██║██████╔╝
# ██╔══╝ ██║ ██║██╔══██╗
# ██║ ╚██████╔╝██║ ██║
# ╚═╝ ╚═════╝ ╚═╝ ╚═╝
# basic loop
for i in 1 2 3 4 5 6 7 8 9 10
do
echo $i
done
# loop ls command results
for var in `ls -alF`
do
echo $var
done
# loop specified number of times
for i in `seq 1 10`
do
echo $i
done
#==============================##==============================#
# CMD FOR for-schleife #
#==============================##==============================#
for i in one two three ; do printf "'$i'," ; done | sed 's/,$//' ; echo
# Prepare a list of items (one two three) for SQL list syntax.
for i in *.jpg; do identify "$i"; done
# Use a for loop to iterate over a list of items (files, numbers, etc) and run processes accordingly.
for i in {1..20} ; do rig|head -1 |tr A-Z a-z;done |while read f l;do echo ${f:0:1}${l}:$(pwgen 12 1);done
# Gen 20 random users/passwords
for file in * ; do echo mv "$file" "`echo $file | tr [:upper:] [:lower:]`"; done
# To give an example this can be used to rename all files in the current directory to lowercase (there are other ways to do this, but this is a decent example) -> Of course you can convert the other way by swapping '[:upper:]' and '[:lower:]'.
for dir in */ ; do echo "${dir%/}" ; done
# Use the */ trick to get only the directories, then use ${dir%/} to remove the trailing / you get
for p in *.tiff; do convert -quality 75 -scale 50% "$p" "${p%%.tiff}.jpg"; echo converted $p; done
# Convert tiff images to rescaled jpg
for w in {1..104} ; do date -d "now - $w weeks" +%Y-%m-%d ; done
# Last 2 years of this weekday. Shorter easier to read version. ;-)
for t in "Wake up" "The Matrix has you" "Follow the white rabbit" "Knock, knock";do pv -qL10 <<<$'\e[2J'$'\e[32m'$t$'\e[37m';sleep 5;done
for i in $(ls -1 /usr/share/man/man1/) ; do p=${i//.1.gz} ; echo -n "$p " ; man $p|egrep "^[\ \t]*--?[a-zA-Z0-9]"|wc -l;done
# option count
for n in 30 41 41 38 41 9999 31 30;do for t in {0..2200};do [[ $(($t%$n)) == 0 ]]&&echo -n $'\xb0'||echo -n $'\x80';done;done>/dev/dsp
# snd
for d in */; do echo -n "$d "; file -b "$d"/* |cut -d' ' -f1 |sort| uniq -c| sort -rn|head -1; done
# Most common type of file per subdir.
for x in -{630..599}; do for z in -{115..130}; do echo "/setblock $x 60 $z minecraft:stone";done;done
# Minecraft make stone floor commands.
for i in {1..10} ; do sleep $(( $RANDOM % 3600 + 1800 )) ; twitter-queueposter.py ; done
# Engage lazy mode.
for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300 $i thumbs/$i ; done
# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPG
for i in 172.16.0.{1..254};do (ping -c1 $i > /dev/null && echo $_) &done > pinged-hosts
# Quickly scan network without using nmap, etc.
for p in *.jpg; do ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi; done
# Make slideshow from *.jpg
for f in *; do b=$(echo "$f" | tr '[A-Z]' '[a-z]'); mv "$f" "$b"; done
# Lower case all files in a folder.
for f in *.mp4; do echo "processing $f"; bname=$(basename $f); ffmpeg -i "$f" "$bname.wav"; done
# Convert MP4 to WAV.
for d in */; do echo $d; cd $d; npm outdate; cd - > /dev/null; done
# NPM outdate for projects in dir.
for i in *.jpg; do identify "$i"; done
# Use a for loop to iterate over a list of items (files, numbers, etc) and run processes accordingly.
for i in {1..20} ; do rig|head -1 |tr A-Z a-z;done |while read f l;do echo ${f:0:1}${l}:$(pwgen 12 1);done
# Gen 20 random users/passwords
for file in * ; do echo mv "$file" "`echo $file | tr [:upper:] [:lower:]`"; done
# To give an example this can be used to rename all files in the current directory to lowercase (there are other ways to do this, but this is a decent example) -> # Of course you can convert the other way by swapping '[:upper:]' and '[:lower:]'.
for dir in */ ; do echo "${dir%/}" ; done
# Use the */ trick to get only the directories, then use ${dir%/} to remove the trailing / you get
for i in *.jpg;do printf "$i %s\n" $(convert "$i" -scale 1x1\! -format '%[pixel:u]' info:- ) ;done |tee -a color-indexes.txt
# Major colors
for x in $(docker images | awk '$1 ~ "<none>" {print $3}'); do docker rmi $x; done
# Deletes orphaned docker images.
for d in */; do echo $d; cd $d; npm outdate; cd - > /dev/null; done
# NPM outdate for projects in dir.
for f in *.mp4; do echo "processing $f"; bname=$(basename $f); ffmpeg -i "$f" "$bname.wav"; done
# Convert MP4 to WAV.
for i in one two three ; do printf "'$i'," ; done | sed 's/,$//' ; echo
# Prepare a list of items (one two three) for SQL list syntax.
for i in {1..254}; do ping -c 1 -W 1 10.1.1.$i | grep 'from'; done
#Ping scanning without nmap
#Usefull for when you don't have nmap and need to find a missing host.
#Pings all addresses from 10.1.1.1 to 10.1.1.254, modify for your subnet.
#Timeout set to 1 sec for speed, if running over a slow connection you should raise that to avoid missing replies.
#This will clean up the junk, leaving just the IP address:
for i in {1..254}; do ping -c 1 -W 1 10.1.1.$i | grep 'from' | cut -d' ' -f 4 | tr -d ':'; done
for i in $(seq 4 65);do echo -n "${pi:0:$i}.com: ";whois ${pi:2:$((i-2))}.com|grep --col=no "rant Na"||echo;sleep 5;done #pi domain owners
for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300 $i thumbs/$i ; done
# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPG
# Right, so you will probably want to use 3[0-4]??.JPG or 3[0-4][0-9][0-9].JPG to be more precise.
for x in $(docker images | awk '$1 ~ "<none>" {print $3}'); do docker rmi $x; done
# Deletes orphaned docker images.
for i in *.jpg;do printf "$i %s\n" $(convert "$i" -scale 1x1\! -format '%[pixel:u]' info:- ) ;done |tee -a color-indexes.txt
# Major colors
for i in {1..20} ; do rig|head -1 |tr A-Z a-z;done |while read f l;do echo ${f:0:1}${l}:$(pwgen 12 1);done
# Gen 20 random users/passwords
for i in *.jpg; do identify "$i"; done
# Use a for loop to iterate over a list of items (files, numbers, etc) and run processes accordingly.
for i in $(seq 4 65);do echo -n "${pi:0:$i}.com: ";whois ${pi:2:$((i-2))}.com|grep --col=no "rant Na"||echo;sleep 5;done #pi domain owners
for f in *; do b=$(echo "$f" | tr '[A-Z]' '[a-z]'); mv "$f" "$b"; done
# Lower case all files in a folder.
for dir in */ ; do echo "${dir%/}" ; done
# Use the */ trick to get only the directories, then use ${dir%/} to remove the trailing / you get
for i in 172.16.0.{1..254};do (ping -c1 $i > /dev/null && echo $_) &done > pinged-hosts
# Quickly scan network without using nmap, etc.
for p in *.jpg; do ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi; done
# Make slideshow from *.jpg
for i in {1..10} ; do sleep $(( $RANDOM % 3600 + 1800 )) ; twitter-queueposter.py ; done
# Engage lazy mode.
for x in -{630..599}; do for z in -{115..130}; do echo "/setblock $x 60 $z minecraft:stone";done;done #Minecraft make stone floor commands.
#
for p in *.tiff; do convert -quality 75 -scale 50% "$p" "${p%%.tiff}.jpg"; echo converted $p; done
# Convert tiff images to rescaled jpg
for d in */; do echo -n "$d "; file -b "$d"/* |cut -d' ' -f1 |sort| uniq -c| sort -rn|head -1; done
# Most common type of file per subdir.
for n in 30 41 41 38 41 9999 31 30;do for t in {0..2200};do [[ $(($t%$n)) == 0 ]]&&echo -n $'\xb0'||echo -n $'\x80';done;done>/dev/dsp
# snd
for t in "Wake up" "The Matrix has you" "Follow the white rabbit" "Knock, knock";do pv -qL10 <<<$'\e[2J'$'\e[32m'$t$'\e[37m';sleep 5;done
#
for w in {1..104} ; do date -d "now - $w weeks" +%Y-%m-%d ; done
# Last 2 years of this weekday. Shorter easier to read version. ;-)
for i in $(ls -1 /usr/share/man/man1/) ; do p=${i//.1.gz} ; echo -n "$p " ; man $p|egrep "^[\ \t]*--?[a-zA-Z0-9]"|wc -l;done
# option count
for dev in `grep dev /etc/fstab | grep -v \#`; do fsck ${dev}; done
# fsck my life - To do a filesystem check on all of your partitions, heres a quick one-liner. It parses out /etc/fstab for the partitions and runs a fsck on them.
for dev in `grep dev /etc/fstab | grep -v \# | grep ext3 |cut -f1 -d " "`; do echo ${dev}; done
# fsck my life - Or a suggested change to pull just the dev files and remove any non-ext3(insert your preferred file system format) file systems, i.e. /dev/cdrom or swap. This will not work with RHEL as Red Hat uses LABELs instead of device paths in the /etc/fstab file. Or This is what fsck does by default. Okay in actual fact it uses the values on the right to decide whether to fcsk or not (man fstab). You also probably dont want to do this on mounted filesystems (fsck -M will prevent this), and most systems already have this at startup. ALSO, fsck when given a list of devices will run in parallel against devices it feels are safely on different physical devices for extra speed.
for i in *.txt; do mv $i ${i%%.txt}.html; done
# Change extension on a group of files using only bash builtins an -> To change the extension on a group of files using only bash builtins and mv
for i in *.txt; do mv "$i" "${i%%.txt}".html; done
# you forgot the quotes also see: http://www.shell-fu.org/lister.php?id=27
for (( i = 0 ; i < 12; i++ )); do touch $RANDOM; done
# Often it can be handy to have a few files to test another script on. A quick way to do this is to create some empty files with random names -> Just change the number (12) to give the required number of files.
# or
for (( i = 0 ; i < 12; i++ )); -- long
# or
for i in $(seq 0 12); -- short
# or
for i in `seq 12`; do touch $RANDOM; done
# is even shorter, but not all systems have the 'seq' command - hence the original can still be useful. in the same vain as `seq 12` - for in in {1..12}; do touch $RANDOM;done ->having files named against $RANDOM seems pretty useless for testing :P in any case if you really want random use "mktemp" that is collision-safe at least.
for((I=0;J=--I;))do clear;for((D=LINES;S=++J**3%COLUMNS,--D;))do printf %*s.\\n $S;done;sleep 1;done
# 100 byte bash snow field
for((I=0;J=--I;))do clear;for((D=LINES;S=++J**3%COLUMNS,--D;))do printf %*s*\\n $S;done;sleep 0.1;done
# with flakes
for((I=0;J=--I;))do clear;for((D=LINES;S=++J**3%COLUMNS,--D;))do printf %*s❄\\n $S;done;sleep 0.1;done
# with snowflake
for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300 $i thumbs/$i ; done
# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPG
for i in `pip list -o --format legacy|awk '{print $1}'` ; do pip install --upgrade $i; done
# Automatically update all the installed python packages
for p in $(fuser -m /) ; do lsof -p $p ; done
#
for file in myDir/* ; do echo; echo "---$file--" ; cat $file ; done
# cat all the files in a directory
# Uppercase to lowercase with tr - The 'tr' command can be used to quickly convert uppercase to lowercase and vice versa. This is done with: tr [:upper:] [:lower:] - To give an example this can be used to rename all files in the current directory to lowercase (there are other ways to do this, but this is a decent example): Of course you can convert the other way by swapping '[:upper:]' and '[:lower:]'.
for file in * ; do echo mv "$file" "`echo $file | tr [:upper:] [:lower:]`"; done
t=$((COLUMNS*LINES-COLUMNS));r=$((RANDOM%t));printf "\e[32m";for i in $(seq $t);do [[ $i == $r ]]&&printf "🍀"||printf "☘";done
# find 4-leaf
t=$(($(tput cols)/3));for FR in $(seq $(tput lines));do printf "\e[44m%${t}s\e[47m%${t}s\e[41m%${t}s\e[0m\n";done
# French Flag #BastilleDay
o="-vvvvvv";for i in 0 {2..7}; do c="aptitude ${o:0:$i} moo";echo "$ $c"; $c; done
# Discover the Super Cow Powers of aptitude.
for i in {1..100}; do convert -background lightblue -fill blue -size 100x100 -pointsize 24 -gravity center label:$i $i.jpg; done
# Create test images
stf=$(date +%s.%N);st=${stf/.*/};sn=%{stf/*./};for ((;;));do ctf=$( date +%s.%N );ct=${ctf/.*/};cn=${ctf/*./}; echo -en "\r$(echo "scale=3; $ctf-$stf" | bc)";done
# Chronometer A way for tracking times in bash
stf=$(date +%s.%N);for ((;;));do ctf=$( date +%s.%N );echo -en "\r$(date -u -d "0 $ctf sec - $stf sec" "+%H:%M:%S.%N")";done
# Chronometer in hour format Shorter and faster...
NUM=-1; while NUM=`echo $NUM + 1 | bc`; do echo $NUM && sleep 1; done
# Chronometer - Chronometer using the bc calculator.
stf=$(date +%s.%N);st=${stf/.*/};sn=%{stf/*./};for ((;;));do ctf=$( date +%s.%N );ct=${ctf/.*/};cn=${ctf/*./}; dtf=$(echo "scale=3; $ctf-$stf" | bc); dt=${dtf/.*/}; dt=${dt:=0};echo -en "\r$(date -u -d @$dt "+%H:%M:%S.${dtf/*./}")";done
# Chronometer in hour format Just add a format to chronometer in bash
for file in P*.JPG; do convert $file -resize 1280 n-$file; for file in _P*.JPG; do convert $file -resize x1280 n-$file; done
# Some image bash processing
for in $i(cat list.txt); do ssh user@$i 'bash command'; done
# In the above example you will need to change “user” with the actual user with which you will be logging and “bash command” with the actual bash command you wish to execute. The method is better working when you are using passwordless authentication with SSH key to your machines as that way you will not need to enter the password for your user over and over again.
# Note that you may need to pass some additional parameters to the SSH command depending on your Linux boxes setup.
for i in G M K; do du -ah | grep [0-9]$i | sort -nr -k 1; done | head -n 11
# You can use above command only if GNU/sort is installed. For other UNIX systems should use the below command.
for i in 1F6{0..4}{{0..9},{A..F}} ; do printf "\\\\U$i \U$i\n" ; done
# Print the Unicode emoticons block codes and symbols.
for repo in repos/* ; do git -C "$repo" log | grep ^Author: ; done | sort | uniq
# Generate list of all authors in git repos under repos/
for domain in $(cat dominios.txt); do nslookup -type=mx $domain ; done >ejemplo.txt
# Enumerar Registros MX
for i in log.{48..1}.gz ; do printf "$i\t" ; zgrep problem $i | wc -l ; done
# Generate line stats of a problem over time in old logs. FIXED
for i in `seq -w 1 20`; do echo $i; done
# BASH For Loop - A bash script to loop 1 through 20 easily with seq.
for i in *.pdf; do mv "$i" CS749__"$i"; done
# Adding Prefix to File name
for i in $(aws ec2 describe-regions --output text --region "" | cut -f 3); do aws ec2 describe-images --output text --region $i --filter Name=name,Values=myimage | cut -f 6 | grep ami* | xargs -I {} aws ec2 deregister-image --region $i --image-id {};done
# Cross-region delete aws ec2 image
for i in {2018..2025}-{01..12}-13; do [[ $(date --date $i "+%u") == 5 ]] && echo "$i Friday the 13th"; done
# Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy) -> Removed grep and simplified if statement. -- Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale.
for i in *; do I=`echo $i|cut -c 1|tr a-z A-Z`; if [ ! -d "$I" ]; then mkdir "$I"; fi; mv "$i" "$I"/"$i"; done
# Sort files in folders alphabetically -> Creates one letter folders in the current directory and moves files with corresponding initial in the folder.
for y in $(seq 1996 2018); do echo -n "$y -> "; for m in $(seq 1 12); do NDATE=$(date --date "$y-$m-13" +%A); if [ $NDATE == 'Friday' ]; then PRINTME=$(date --date "$y-$m-13" +%B);echo -n "$PRINTME "; fi; done; echo; done
# Calculate days on which Friday the 13th occurs -> Simply change the years listed in the first seq, and it will print out all the months in that span of years that have Friday the 13ths in them.
# This is sample output - yours may be different.
2010 -> August
2011 -> May
2012 -> January April July
2013 -> September December
2014 -> June
2015 -> February March November
2016 -> May
2017 -> January October
2018 -> April July
for y in $(seq 1996 2018); do echo -n "$y -> "; for m in $(seq 1 12); do NDATE=$(date --date "$y-$m-13" +%w); if [ $NDATE -eq 5 ]; then PRINTME=$(date --date "$y-$m-13" +%B);echo -n "$PRINTME "; fi; done; echo; done
# Calculate days on which Friday the 13th occurs -> I removed the dependency of the English language
# This is sample output - yours may be different.
1996 -> setembro dezembro
1997 -> junho
1998 -> fevereiro março novembro
1999 -> agosto
2000 -> outubro
2001 -> abril julho
2002 -> setembro dezembro
2003 -> junho
2004 -> fevereiro agosto
2005 -> maio
2006 -> janeiro outubro
2007 -> abril julho
2008 -> junho
2009 -> fevereiro março novembro
2010 -> agosto
2011 -> maio
2012 -> janeiro abril julho
2013 -> setembro dezembro
2014 -> junho
2015 -> fevereiro março novembro
2016 -> maio
2017 -> janeiro outubro
2018 -> abril julho
for i in {2018..2025}-{01..12}-13; do [[ $(date --date $i +"%u" | grep 5) != 5 ]] || echo "$i Friday the 13th"; done
# Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy)
Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale. Hide sample output
# This is sample output - yours may be different.
2018-04-13 Friday the 13th
2018-07-13 Friday the 13th
2019-09-13 Friday the 13th
2019-12-13 Friday the 13th
2020-03-13 Friday the 13th
2020-11-13 Friday the 13th
2021-08-13 Friday the 13th
2022-05-13 Friday the 13th
2023-01-13 Friday the 13th
2023-10-13 Friday the 13th
2024-09-13 Friday the 13th
2024-12-13 Friday the 13th
2025-06-13 Friday the 13th
for i in {2018..2022}-{01..12}-13; do date --date $i +"%Y %B %w" | sed '/[^5]$/d; s/ 5*$//'; done
# Calculate days on which Friday the 13th occurs -> Alter the years in the first brace expansion to select your year range. Modify date format to your liking but leave " %w" at the end. Hide sample output
# This is sample output - yours may be different.
2018 April
2018 July
2019 September
2019 December
2020 March
2020 November
2021 August
2022 May
# Batch renaming in Terminal (e.g. bash) using RegEx
# Example: replace every capital letter with 'abc', only changing m4a-files
for file in *.m4a ; do mv -vf "$file" "`echo $file | sed -E 's/[A-Z]/abc/g'`" ; done
# Sublime-Text snippet:
<snippet>
<content><![CDATA[
for file in *.${1:m4a} ; do mv -vf "\$file" "`echo \$file | sed -E 's/${2:[A-Z]}/${0:abc}/g'`" ; done
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>rename</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>
#-----------------------------------------------------------------------------------------------------------------------------#
#Remove stored .zip archive passwords from Windows credential manager
#Do not want to log out but you do want to get rid of a stored .zip file password in Windows? This will do that.
for /f "tokens=2-3 delims==" %G IN ('cmdkey /list ^| find ".zip"') DO cmdkey /delete:"%G=%H"
for i in $(qm list | awk '{ print $1 }' | grep -v VMID); do echo "Unlocking:" $i; qm unlock $i; echo "Unlocked"; done
# loop files with SPACES on their names - use '*' instead of 'ls'
for f in *;do echo $f;done
for i in {1..50} ; do d=$(( RANDOM % 29950 + 6575 )) ; date -d "$d days ago" +"%F"; done
# Create 50 random dates that are between 18 - 100 years ago. Used to create example birth date data.
for i in $(qm list | awk '{ print $1 }' | grep -v VMID); do echo "Unlocking:" $i; qm unlock $i; echo "Unlocked"; done
# Unlock VMs in Proxmox - Unlock your VMS to avoid problems after some failed tasks ended.
# This is sample output
...
Unlocking: 10098
Unlocked
Unlocking: 10120
Unlocked
Unlocking: 11018
Unlocked
Unlocking: 20003
Unlocked
Unlocking: 20023
...
# Calculate days on which Friday the 13th occurs (inspired from the work of the user justsomeguy) - Removed grep and simplified if statement. -- Friday is the 5th day of the week, monday is the 1st. Output may be affected by locale. Show Sample Output
for i in {2018..2025}-{01..12}-13; do [[ $(date --date $i "+%u") == 5 ]] && echo "$i Friday the 13th"; done
# Day of the week of your birthday over the years.-> Do you ever want to know which day of week was your birhday! Now you can check that with this command, just set your birh date at the beginning (My bday in the example) and the dates will be revealed. ;) Show Sample Output
# ...
# 1999 -> Thursday
# 2000 -> Saturday
# 2001 -> Sunday
# 2002 -> Monday
# ...
DAY=01; MONTH=07; YEAR=1979; CURRENT_YEAR=$(date +%Y); for i in $(seq $YEAR $CURRENT_YEAR); do echo -n "$i -> "; date --date "$i-$MONTH-$DAY" +%A; done
# Count number of javascript files in subdirectories. -> I wanted to count and display the top directories containing JavaScript files in some of my project. Here it is. Maybe it can be written to more simply syntax by using find -exec...
for f in `find . -type d`; do pushd . > /dev/null ; echo -e `cd $f ; find . -name \*\.js | wc -l` "\t" $f | grep -v ^0 ; popd >/dev/null; done | sort -n -k 1 -r | less
# zip-dir - zip directories - Zip all top level directories
for i in */; do if [ ! -f "${i%/}.zip" ]; then zip -r "${i%/}.zip" "$i"; fi done
for i in 198.187.190.{0..255}; do a=$( dig +short -x $i ); printf "$i: %s\n" "$a"; done
# Print a list of reverse DNS records for a subnet.
for i in p{1..3}p{1..8}; do timeout 5m tcpdump -c 5000 -i $i -w tcpdump-${i}-20181127.pcap; done
# Either log 5000 packets (-c 5000) or timeout after 5 minutes (timeout 5m) on each of 24 network tap interfaces. Did this because some interfaces may return nothing.
for i in IMG_3[0-4]*.JPG ; do convert -quality 60 -geometry 300 "$i" "thumbs/$i" ; done
# Make thumbnails of images IMG_3000.JPG - IMG_3499.JPG
for i in {1..254};do (ping -c1 172.16.0.$i > /dev/null && echo $_) & done > pinged-hosts
# Quickly scan 172.16.0.0/24 network without using a more sophisticated tool like nmap.
for p in *.jpg; do ffmpeg -loop_input -f image2 -i $p -t 3 -r 4 -s 1080x720 -f avi - >> slides.avi; done
# Make slideshow from *.jpg
for i in {1..65535};do printf "%x\n" $i;done|while read -r u;do printf "\033[38;5;$((16+$((16#$u))%230))m\u$u\033[0m";done
# Unicode rainbow. Note: This may not work on Macs without changing the syntax.
# Generate a sequence of numbers.
for ((i=1; i<=99; ++i)); do echo $i; done
# Download all .key files from your android device to your pc.
for i in `adb shell "su -c find /data /system -name '*.key'"`; do mkdir -p ".`dirname $i`";adb shell "su -c cat $i" > ".$i";done
# Download all default installed apk files from your android.
for i in $(adb shell pm list packages | awk -F':' '{print $2}'); do adb pull "$(adb shell pm path $i | awk -F':' '{print $2}')"; mv *.apk $i.apk 2&> /dev/null ;done
# Rename all files in lower case
for f in `find`; do mv -v "$f" "`echo $f | tr '[A-Z]' '[a-z]'`"; done
# Silently deletes lines containing a specific string in a bunch of files
# This command will find all occurrences of one or more patterns in a collection of files and will delete every line matching the patterns in every file
for file in $(egrep 'abc|def' *.sql | cut -d":" -f1 | uniq); do sed -i '/abc/d' ./$file ; sed -i '/def/d' ./$file; done
# Convert all flac files in the current directory to mp3 format using "lame"
for i in *.flac; do flac -c -d "$i" | lame -m j -b 192 -s 44.1 - "${i%.flac}.mp3"; done
# Make another user superuser in Ubuntu
for i in $(grep :boss /etc/group | cut -f1 -d:); do adduser wife $i; done
## Alternative one-liners:
# ename all items in a directory to lower case
for i in *; do mv "$i" "${i,,}"; done
# Explanation: Loop over the items in the current directory, and use Bash built-in case modification expansion to convert to lower case.
# Limitations: The case modification extension is available since Bash 4.
# Unpack all of the .tar.bz2 files in current directory
for FILE in *; do tar -jxf $FILE; done
# Explanation:
# for: begins the loop syntax in Bash.
# FILE: can be any variable name you create.
# do: this is the action you are going to tell Bash to perform on each pass of the loop.
# Convert all flac files in the current directory to mp3 format using "lame"
for i in *.flac; do flac -c -d "$i" | lame -m j -b 192 -s 44.1 - "${i%.flac}.mp3"; done
Calculate the average execution time (of short running scripts) with awk
for i in {1..10}; do time some_script.sh; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
# Explanation:
# The for loop runs some_script.sh 10 times, measuring its execution time with time
# The stderr of the for loop is redirected to stdout, this is to capture the output of time so we can grep it
# grep ^real is to get only the lines starting with "real" in the output of time
# sed is to delete the beginning of the line up to minutes part (in the output of time)
# For each line, awk adds to the sum, so that in the end it can output the average, which is the total sum, divided by the number of input records (= NR)
# Limitations:
The snippet assumes that the running time of some_script.sh is less than 1 minute, otherwise it will not work at all. Depending on your system, the time builtin might work differently. Another alternative is to use the time command /usr/bin/time instead of the bash builtin.
# Check the performance of a script by re-running many times while measuring the running time
for i in {1..10}; do time curl http://localhost:8000 >/dev/null; done 2>&1 | grep real
# Explanation:
# {1..10} creates a sequence from 1 to 10, for running the main script 10 times
# 2>&1 redirects stderr to stdout, this is necessary to capture the "output" of the time builtin
# Sort du output in Human-readable format
for i in G M K; do du -hsx * | grep "[0-9]$i\b" | sort -nr; done 2>/dev/null
# Explanation:
# The reason to use a for loop is to sort results with G or M or K values separately, otherwise sort -n would just sort everything by the numbers regardless of G M K suffix.
# grep "[0-9]$i\b" matches lines containing a digit followed by G or M or K followed by a "word boundary"
# Sort du output in Human-readable format
for i in G M K; do du -hsx * | grep "[0-9]$i\b" | sort -nr; done 2>/dev/null
# Explanation:
# The reason to use a for loop is to sort results with G or M or K values separately, otherwise sort -n would just sort everything by the numbers regardless of G M K suffix.
# grep "[0-9]$i\b" matches lines containing a digit followed by G or M or K followed by a "word boundary"
# Sort du output in Human-readable format
for i in $(echo -e 'G\nM\nK'); do du -hsx /* 2>/dev/null | grep '[0-9]'$i | sort -rn; done
# Explanation:
# echo -e prints G for Gigabytes, M for Megabytes and K for Kilobytes in a line each.
# 2>/dev/null send stderr to /dev/null
# sort -rn sorts in reverse numerical order. Largest first
# Sort du output in Human-readable format
for i in G M K; do du -hsx * | grep "[0-9]$i\b" | sort -nr; done 2>/dev/null
# Explanation:
# The reason to use a for loop is to sort results with G or M or K values separately, otherwise sort -n would just sort everything by the numbers regardless of G M K suffix.
# grep "[0-9]$i\b" matches lines containing a digit followed by G or M or K followed by a "word boundary"
# Sort du output in Human-readable format
for i in $(echo -e 'G\nM\nK'); do du -hsx /* 2>/dev/null | grep '[0-9]'$i | sort -rn; done
# Explanation:
# echo -e prints G for Gigabytes, M for Megabytes and K for Kilobytes in a line each.
# 2>/dev/null send stderr to /dev/null
# sort -rn sorts in reverse numerical order. Largest first
# Run command multiple times with a for loop and a sequence expression
for i in {1..10}; do date; sleep 1; done
# Explanation: This is just a regular for loop with a sequence expression. A sequence expression has the form {x..y[..incr]}, where x and y are either integers or single characters, and incr an optional increment.
# More examples:
# {a..f} = a b c d e f
# {a..f..2} = a c e
# {0..1}{0..1} = 00 01 10 11
# Limitations: do not try a large range like {1..10000000000000000}, it may render your computer unusable until killed.
# Log and verify files received via FTP
for i in $(cat /var/log/vsftpd.log | grep $DATE_TIME | grep UPLOAD | grep OK); do ls /FTP/HOME/$i >> /dev/null 2> \&1; if \[ $? = 0 \]; then echo "$i" >> $FILES_OK_UPLOADS.log; else echo "$DATE ERROR: File $i not found" >> $FTP_FILES_NOTOK_$DATE_TIME.log; fi; done
# Create fattal tone mapped images from a directory of raw images
for img in /path/to/rawimages/*.RW2; do pfsin ${img} | pfssize -x 1024 -y 768 | pfstmo_fattal02 -v -s 1 | pfsout /path/to/finished/${img%%}.jpg; done
# Explanation: for img in /path/to/rawimages/*.RW2; do Loop through image directory
pfsin ${img} | read the raw image
pfssize -x 1024 -y 768 | resize it to 1024x768 because fattal looks better at low resolutions
pfstmo_fattal02 -v -s 1 | use the fattal tone mapping operator, be verbose and saturation value of 1
pfsout ./path/to/finished/${img%%}.jpg; done output and rename the file as a jpg.
# Examples of fattal tone mapped images http://goo.gl/IayQQ - pfstools website http://pfstools.sourceforge.net/
# Limitations: Portrait orientation images need to be processed -x 768 -y 1024
# Rename all files in a directory to upper case
for i in *; do mv "$i" "${i^^}"; done
# Explanation: Loop over the items in the current directory, and use Bash built-in case modification expansion to convert to upper case.
# Limitations: The case modification extension is available since Bash 4.
# Rename all items in a directory to lower case
for i in *; do mv "$i" "${i,,}"; done
# Explanation: Loop over the items in the current directory, and use Bash built-in case modification expansion to convert to lower case.
# Limitations: The case modification extension is available since Bash 4.
# How to expand a CIDR notation to its IPs
for j in $(seq 0 255); do for i in $(seq 0 255) ; do seq -f "10.$j.$i.%g" 0 255; done; done
# Explanation: Using two for loops to create second & third block of IP and finally through a formatted seq to printf the output. More efficient/using less memory than using {..} (range).
# Limitations: seq is not available by default in some systems.
# Find which log files contain or do not contain a specific error message
for i in *.log; do grep OutOfMemo $i >/dev/null && echo $i oom || echo $i ok; done
# Explanation: In this example I was looking for a list of log files which contain or do not contain a stack trace of OutOfMemoryError events.
# for i in *.log is to loop over the list of files.
# For each file, I run grep, but redirect the output to /dev/null, as I do not need that, I just want to see a "yes or no" kind of summary for each file
# grep exits with success if it found any matching lines, otherwise with failure. Using the pattern cmd && success || failure, I echo the filename and the text "oom" in case of a match, or "ok" otherwise
# Remarks:
# Using grep -q is equivalent to redirecting output to /dev/null, but might not be supported in all systems
# grep -l can be used to list files with matches, and grep -L to list files without matches, but the latter does not exist in some implementations of grep, such as BSD
# I realized it a bit late, but grep -c shows a count of the matches, so actually it could have been a suitable and simpler solution
# Limitations: could be put in a loop like this
for A in $(printf %08X'\n' 256 255); do echo $A | grep -o .. | tac | tr -d '\n'; done
# Convert directory of videos to MP4 in parallel
for INPUT in *.avi ; do echo "${INPUT%.avi}" ; done | xargs -i -P9 HandBrakeCLI -i "{}".avi -o "{}".mp4
# Explanation: This oneliner uses the wonderful Handbrake program to convert videos. We convert a directory of AVIs at a time, in parallel. The first three bits ("for INPUT...done |") lists the AVI files in the current directory, then uses a Bash function to strip off the suffix. It then sends each video file name to the next part.
# The next part of the command (| xargs ...) runs our converter in parallel. The "-i" flag says take each input (video file name) and stick it in the "{}" parts of the xargs command. The parallel option lets us run up to 9 commands at the same time ("-P9").
# The last part (HandBrakeCLI -i "{}".avi -o "{}".mp4) converts a single video to MP4 format. The two open-close curly braces are replaced with xargs, once per input video file. The first run through will be "HandBrakeCLI -i "input1".avi -o "input1".mp4", next will be "HandBrakeCLI -i "input2".avi -o "input2".mp4", etc.
# Convert all flac files in dir to mp3 320kbps using ffmpeg
for FILE in *.flac; do ffmpeg -i "$FILE" -b:a 320k "${FILE[@]/%flac/mp3}"; done;
# Explanation: It loops through all files in current directory that have flac extension and converts them to mp3 files with bitrate of 320kpbs using ffmpeg and default codec.
# Generate a sequence of numbers
for ((i=1; i<=10; ++i)); do echo $i; done
# Explanation: This is similar to seq, but portable. seq does not exist in all systems and is not recommended today anymore. Other variations to emulate various uses with seq:
# seq 1 2 10
for ((i=1; i<=10; i+=2)); do echo $i; done
# seq -w 5 10
for ((i=5; i<=10; ++i)); do printf '%02d\n' $i; done
# Delete static and dynamic arp for /24 subnet
for i in {1..254}; do arp -d 192.168.0.$i; done
# Explanation: Simply loop from 1 to 254 and run arp -d for each IP address in the 192.168.0.0/24 network.
# Create a txt files with 10000 rows
for FILE in *.full ; do split -l 100000 $FILE; mv -f xaa `echo "$FILE" | cut -d'.' -f1`.txt; rm -f x*; done
# Explanation: for loop will go trough every file that is finished with ".full" split that in file in files of 100000 rows. Rename the first one as input name but deleting the extension and adding ".txt" as extension. As last stem it will delete the rest of split files.
# Up all docker services as detached mode over all immediate subdirectories
for dir in $(ls -d */); do eval $(cd $PWD/$dir && docker-compose up -d && cd ..); done;
# Explanation: Supposing that you are in a directory that contains many subdirectories with a docker-compose file each one and instead of up one by one manually you want run all at time, well this is a helpful command for this purpose
# Take values from a list (file) and search them on another file
for ITEM in `cat values_to_search.txt`; do (egrep $ITEM full_values_list.txt && echo $ITEM found) | grep "found" >> exit_FOUND.txt; done
# Explanation: This line :) searches values taken from a file (values_to_search.txt) by scanning a full file values list . If value found, it is added on a new file exit_FOUND.txt. Alternatively, we can search for values from the list 1 which does NOT exists on the list 2, as bellow:
for ITEM in cat values_to_search.txt; do (egrep $ITEM full_values_list.txt || echo $ITEM not found) | grep "not found">> exit_not_found.txt; done
# Limitations:
No # Limitations:
-
for i in {1..12} $(grep ^ru <<<$LANG);do printf "\e[32m%10s{\e[31m@\n\e[0m"|tr " " =; done
# Is your sweetheart a shell user? Give them an ASCII/ANSI bouquet. Provide an extra one for Russian speakers because they prefer odd quantities of flowers. Add to their shell rc file. Mehr jessie frazelle hat cron mom retweetet I have to google the way the fucking arrows and numbers go for “2>&1” every damn time, ie “redirect stderrr to stdout”jessie frazelle hat hinzugefügt, cron mom
for a in *.pdf ; do pdfcrop --margins '0 -575 0 -10' $a `basename $a .pdf`-notes.pdf ; done
# pdfcrop came to my rescue to extract a section at the bottom of each page on a large number of pdf files: https://github.com/mvp/uhubctl
# Linux users with an compatible USB hub can use uhubctl to turn on/off that USB fan, light, vacuum cleaner.
for f in *.zip; do unzip -d "${f%*.zip}" "$f"; done
# Make a dedicated folder for each zip file {f%*.zip} strips off the extension from zip filenames
# Create a txt files with 10000 rows
for FILE in *.full ; do split -l 100000 $FILE; mv -f xaa `echo "$FILE" | cut -d'.' -f1`.txt; rm -f x*; done
# Up all docker services as detached mode over all immediate subdirectories
for dir in $(ls -d */); do eval $(cd $PWD/$dir && docker-compose up -d && cd ..); done;
# I wrote a countdown alarm with graphic output for cooking with one line of code, the power of command line:
clear; for i in `seq 60 -1 1`; do banner $i; sleep 1; clear; done ; play -n synth .8 sine 4100 fade q 0.1 .3 0.1 repeat 3
# Interactively delete broken links in folder
for f in $( file . | grep broken | cut -d':' -f 1 ); do rm -i $f; done
# Prepend to filename
for file in ; do mv $file 'Pandoras_Box_'$file ; done
# Undo above (delimiter arg may need to be tweaked here)
for file in ; do mv $file `echo $file | cut -f3 -d_` ; done
# Replace all spaces with underscores in file name
# For recursive see http://stackoverflow.com/questions/2709458/bash-script-to-replace-spaces-in-file-names
for f in \ ; do mv "$f" "${f// /_}"; done
# files for ls to digest... in which case the same command would work with echo instead:
for i in $(echo [0-9]*.png); do mv $i $(echo $i | awk -F".png" '{ printf "%05d\n",$1}').png;done
# Good for upto almost 10k numbered filenames
for i in $(ls [0-9]*.png); do mv $i $(echo $i | awk -F".png" '{ printf "%05d\n",$1}').png;done
# Sometimes you want to generate a list of valid dates for the year. Use {0..365} on a leap year. This uses GNU date syntax.
for d in {0..364} ; do date -d "2019-01-01 + $d days" +%Y%m%d ; done
# Fix some files (matching 3.png, 4.png, ... 9.png) so that they have leading zeros for proper ordering.
for i in [3-9].png ; do mv $i 0$i ; done
#shell bash iterate number range with for loop
# "seq" has an additional parameter to use as INCREMENT. # seq FIRST INCREMENT LAST https://linux.die.net/man/1/seq
for i in $(seq 1 5) ; do echo $i ; done
#This is sample output - yours may be different.
1
2
3
4
5
#Block all IPv4 addresses that has brute forcing our ssh server
#For ipv6 use: grep -oE "\b([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\b"
for idiots in "$(cat /var/log/auth.log|grep invalid| grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b')"; do iptables -A INPUT -s "$idiots" -j DROP; done
#shell bash iterate number range with for loop
#Bashs arithmetic evaluation.
for((i=1;i<=10;i++)){ echo $i; }
#shell bash iterate number range with for loop
for i in {1..10}; do echo $i; done
#shell bash iterate number range with for loop
rangeBegin=10; rangeEnd=20; for ((numbers=rangeBegin; numbers<=rangeEnd; numbers++)); do echo $numbers; done
#shell bash iterate number range with for loop
#iterating range of numer with for loop in shell or bash
rangeBegin=10; rangeEnd=20; for numbers in $(eval echo "{$rangeBegin..$rangeEnd}"); do echo $numbers;done
# This is sample output - yours may be different.
10
11
12
13
14
15
16
17
18
19
20
# convert raw camera image to jpeg - raw image created by canon digital camera. Install using apt-get install ufraw
for i in *.CR2; do ufraw-batch $i --out-type=jpeg --output $i.jpg; done;
# Scan all open ports without any required program
for i in {1..65535}; do (echo < /dev/tcp/127.0.0.1/$i) &>/dev/null && printf "\n[+] Open Port at\n: \t%d\n" "$i" || printf "."; done
# Massive change of file extension (bash) - Change the file extension in batch. Useful to create output file names with same input name but distinct extension by including logic inside the loop
for file in *.txt; do mv "$file" "${file%.txt}.xml"; done
# Generate a sequence of numbers
for i in {1..10};do echo $i;done
# Rename all files in a directory to the md5 hash
for i in *; do sum=$(md5sum $i); mv -- "$i" "${sum%% *}"; done
# shell bash iterate number range with for loop -> Bash's arithmetic evaluation.
for((i=1;i<=10;i++)){ echo $i; }
# shell bash iterate number range with for loop
for i in {1..10}; do echo $i; done
# shell bash iterate number range with for loop -> "seq" has an additional parameter to use as INCREMENT.
# seq FIRST INCREMENT LAST https://linux.die.net/man/1/seq
for i in $(seq 1 5) ; do echo $i ; done
# Sample output
# 1
# 2
# 3
# 4
# 5
# get all Google ipv4/6 subnets for a iptables firewall for example (updated version) - google has added 2 more netblocks...
for NETBLOCK in $(echo _netblocks.google.com _netblocks2.google.com _netblocks3.google.com); do nslookup -q=TXT $NETBLOCK ; done | tr " " "\n" | grep ^ip[46]: | cut -d: -f2- | sort
# Sample output
# 108.177.8.0/21
# 108.177.96.0/19
# 209.85.128.0/17
# 216.239.32.0/19
# 216.58.192.0/19
# 2404:6800:4000::/36
# 2c0f:fb50:4000::/36
# 35.190.247.0/24
# 66.249.80.0/20
# 72.14.192.0/18
# 74.125.0.0/16
# Find a file and then copy to tmp folder - Select only the files with given name and copy them to /tmp/ folder.
for file in `ls | grep -i 'mumbai|pune|delhi'` ; do cp $file /tmp/ ; done
# Massive change of file extension (bash) - Using bash parameters expansion
for file in *.txt; do mv "${file%.txt}{.txt,.xml}"; done
#==============================##==============================#
# CMD for #
#==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command for in a clear format. This allows users to quickly access the needed information for for without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for for are a valuable resource to work efficiently and purposefully.
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
█║▌│║█║▌★ KALI ★ PARROT ★ DEBIAN 🔴 PENTESTING ★ HACKING ★ █║▌│║█║▌
██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗███████╗██████╗
████████╗██╔══██╗██╔═══██╗╚██╗██╔╝██╔════╝██╔══██╗
╚██╔═██╔╝██║ ██║██║ ██║ ╚███╔╝ █████╗ ██║ ██║
████████╗██║ ██║██║ ██║ ██╔██╗ ██╔══╝ ██║ ██║
╚██╔═██╔╝██████╔╝╚██████╔╝██╔╝ ██╗███████╗██████╔╝
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═════╝
█║▌│║█║▌ WITH COMMANDLINE-KUNGFU POWER █║▌│║█║▌
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.