Ravi Sagar | Home | Blog

Mastering Shell scripting

Table of Contents

1 Iterate files in a folder

for f in *.jpg; do echo ${f}; done;

2 Rename files in a directory

Now let us say you want to remove a prefix like small_ from all your file then you can do something like this.

for f in *.mp4; do mv ${f} ${f/small_}; done;

3 DONE Find and copy files from a directory based on creation date

find /srouce/directory/ -type f -newermt 2022-11-12 -exec cp {} /target/directory/ \;

4 Read lines from a text file

This is one of the most useful thing. You may need to read lines from a file and then do something with those line. It could be file paths or anything else.

while read LINE; do echo $LINE; done < list-video.txt;

5 Copy mpd playlist songs to a directory

I love listening to music using mpd which works great but sometimes I prefer syncing and want to copy my favourite songs from my mpd playlists to a specific directory - it could be a mounted mobile directory or ~/tmp or a mounted usb drive.

while read LINE; do cp ~/myfiles/music/"$LINE" ~/tmp/; done < ~/myfiles/music/playlists/feel-good.m3u

Wow shell is so cool ;)

6 Similarly you can iterate over file path returned by another command.

mpc search any nelly | while read -r LINE; do echo  music/"$LINE"; done;

Super cool isn't it? Here I was trying to search a song.

7 DONE Get file name or file extension

If you are iterating files in a directory and filename is the variable then you can get the file name or file extension easily.


Reference: stackoverflow

8 Search for an image pattern in files in a directory

grep -inH ".png" *.org | cut -d ":" -f 4

-i: ignore case -n: print line number -H: print file name

9 Common errors

  • Bash script and /bin/bashM: bad interpreter: No such file or directory
sed -i -e 's/\r$//' scriptname.sh