UP | HOME
Ravi Sagar | Home | Blog

Mastering Shell scriptring

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 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;

4 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 ~/music/"$LINE" ~/tmp/; done < music/playlists/feel-good.m3u

Wow shell is so cool ;)

5 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.

6 Get file name or file extension

extension="${filename##*.}"
filename="${filename%.*}"

Reference: stackoverflow

7 Common errors

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