Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass a directory as an argument to a for loop in bash?

Tags:

directory

bash

I have a simple bash script, simple.sh, as follows:

#/usr/local/bin/bash
for i in $1
   do
       echo The current file is $i
   done

When I run it with the following argument:

./simple.sh /home/test/*

it would only print and list out the first file located in the directory.

However, if I change my simple.sh to:

#/usr/local/bin/bash
DIR=/home/test/*
for i in $DIR
   do
       echo The current file is $i
   done

it would correctly print out the files within the directory. Can someone help explain why the argument being passed is not showing the same result?

like image 369
SamIAm Avatar asked Apr 02 '13 11:04

SamIAm


2 Answers

If you take "$1", it is the first file/directory, which is possible! You should do it in this way:

for i in "$@"
do
  echo The current file is ${i}
done

If you execute it with:

./simple.sh *

They list you all files of the actual dictionary

"$1" is alphabetical the first file/directory of your current directory, and in the for loop, the value of "i" would be e.g. a1.sh and then they would go out of the for loop! If you do:

DIR=/home/<s.th.>/* 

you save the value of all files/directories in DIR!

like image 84
Oni1 Avatar answered Nov 12 '22 03:11

Oni1


This is as portable as it gets, has no useless forks to ls and runs with a minimum of CPU cycles wasted:

#!/bin/sh
cd $1
for i in *; do
   echo The current file is "$i"
done

Run as ./simple.sh /home/test

like image 2
Jens Avatar answered Nov 12 '22 01:11

Jens