Created
April 28, 2021 16:11
-
-
Save mohamad-wael/3965c19591c03149cb65447aa3fab875 to your computer and use it in GitHub Desktop.
shell for loop example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ c=1 | |
$ echo $c | |
1 | |
$ for c in {1..9}; do echo -n $c; done | |
123456789 | |
# {1..9} will expand to 1 2 3 4 5 6 7 8 9 . | |
# The for loop will loop through these words , | |
# and echo will echo the words . -n is used | |
# to suppress the printing of a new line . | |
$ echo $c | |
9 | |
$ for var in red blue green; do echo $var; done | |
red | |
blue | |
green | |
# Loop through the three words , red blue and | |
# green . Execute the command echo . The result | |
# of executing the for loop is that red , blue | |
# and green are echoed out to the standard output | |
# each on a separate line . | |
$ for file in *; do echo $file; done | |
file1 | |
file2 | |
# print the name of the file in the current | |
# working directory . * is substituted | |
# by the shell with all the file | |
# names in the current directory . | |
$ for file in `echo hey hi | wc` | |
> do | |
> echo $file; | |
> done | |
1 # number of lines | |
2 # number of words | |
7 # number of characters | |
# Execute the echo command , | |
# and redirect its output to | |
# wc , wc will count the number | |
# of lines words and characters , | |
# its output will be | |
# 1 2 7 | |
# loop through the words , and | |
# execute the echo command , and | |
# finally the result of the looping | |
# is displayed to the standard output . | |
# The preceding for loop command | |
# could have been written as : | |
# for file in `echo hey hi | wc`; do echo $file; done | |
# but using the first notation is clearer . | |
# A for loop script named cls , which can | |
# be used to clear the screen . | |
#!/bin/sh | |
# The script can be executed | |
# either using ./cls , or | |
# ./cls 20 | |
counter=${1-25} | |
# Check if an argument is passed | |
# to the script , if so | |
# the counter variable will | |
# have its value , otherwise | |
# the counter is initialized | |
# to a value of 25 | |
for i in `seq 1 $counter` | |
# Use the seq command , to | |
# generate words between 1 | |
# and counter , and loop | |
# over these words , executing | |
# echo , which will just echo | |
# a new line . | |
do | |
echo | |
done | |
# The result of executing the | |
# script is clearing the screen . |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment