Home > front end >  shell script to Output details of all the files in a folder passed as command line argument
shell script to Output details of all the files in a folder passed as command line argument

Time:11-30

So I am trying to write a script in which I will pass folder name as command line argument. The script will search a the files within that folder if it exists and output all the details. My script is as shown

for entry in "$1"/*
do
  data = $(stat $entry)
  echo  "${data}"
done

when I run it gives me following output.

./test.sh: line 3: data: command not found

I have taken the idea from here: Stat command Can someone help what is wrong
I have tried variations like making $entry to entry and echo $data

CodePudding user response:

Your main issue is that you are putting space characters around the equal operator, you must remove them:

  data=$(stat $entry)

It is also good practice to pass variables between quotes in case your folder or any of the filenames contains whitespaces:

  data=$(stat "$entry")

I assume that you are storing the value into a variable because your intent is to use it into an algorithm. If you just want to call stat to list your files, you can simply call:

stat "$1"/*

CodePudding user response:

Remove the spaces in-between data and $(stat entry).

data=$(stat $entry)

you may also simplify this by writing echo "$(stat entry)" and deleting the data variable entirely.

 for entry in "$1*/"; do
        echo "$(stat $entry)"
 done

also, you may need to get a list of every file in $1, because just listing the directory will probably not work. you can find the files in $1 with $(find "$1" -type f)

 for entry in "$(find "$1" -type f)"; do
        echo "$(stat $entry)"
 done

one line: for entry "$(find "$1" -type f)"; do echo "$(stat $entry)"; done

of course, this will not take into account files with spaces in the name. writing an array with a list of files will help in those cases.

edit: add double quotes around $1

  • Related