DEV Community

loading...
Cover image for For Loop to Execute Commands | Shell Scripting

For Loop to Execute Commands | Shell Scripting

rahulmishra05 profile image Rahul Mishra Originally published at programmingport.hashnode.dev ・2 min read

This is a multipart blog article series where I am going to explain the concepts of shell scripting and how to write a shell script in Linux, UNIX or Mac based systems. You can also follow this tutorial blog using windows but for that you have to install a bash from.

In this article we are going to see that how we can use bash commands in shell script with the help of for loop.

  • We can use for loop to execute commands, like this.
for <variable_name> in ls pwd date
do
    echo "----------$<variable_name>----------"
    $<variable_name>
done
Enter fullscreen mode Exit fullscreen mode
  • In this example first ls command will get executed then pwd command and in last date command.
  • Let’s solve another problem we have to print the name of all directories present in any folder using for loop.
for <variable_name> in *
do
    if [ -d $<variable_name> ]
    then 
        echo $<variable_name>
    fi
done
Enter fullscreen mode Exit fullscreen mode
  • Here * will go through each file and every file present in that directory.
  • If condition will check that whether that file is a directory or not, if it is a directory than its name get printed.

Reference code file for this article

So this was all about how can we execute some commands using for loop in shell script. Hope you liked it and learned something new form it.

If you have any doubt, question, quires related to this topic or just want to share something with me, than please feel free to contact me.

πŸ“± Contact Me

Twitter
LinkedIn
Telegram
Instagram

πŸ“§ Write a mail

rahulmishra102000@gmail.com

πŸš€ Other links

GitHub
HackerRank

Discussion (0)

pic
Editor guide