LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   bash scripting question (https://www.linuxquestions.org/questions/linux-general-1/bash-scripting-question-479709/)

Locura 09-02-2006 06:48 AM

bash scripting question
 
Hello all, I'm just getting into scripting and I'm tring to write a script that will operate on each file in a directory, but I'm a little lost on the programming scructure necessary to do so. Basically I want to take each file, check the extension using an if/then statement, then run a command on the file conditionally based on the results of the if/then. Can someone point me in the right direction? I'm clear on how to do an if/then, it's just the part about operating on each file where I'm fuzzy. I tried accepting it as an argument, and then doing a for file in $1, but then I realized that filenames with spaces in them would be affected, so I obviously need a better way of doing this. Any help would be much appreciated.

cs-cam 09-02-2006 07:02 AM

Code:

#!/bin/sh
# this is the line you're interested in
IFS='
'

for $f in `ls`; do
  echo $f
done

exit 0

Not sure if that is the "right" way or not but it's worked for me :)

Andrew Benton 09-02-2006 07:13 AM

Quote:

Originally Posted by Locura
I tried accepting it as an argument, and then doing a for file in $1, but then I realized that filenames with spaces in them would be affected.

The problem with spaces in filenames can be avoided simply by putting double quotes around the variable "$1".
It sounds to me like you need to investigate the command find. These commands checks whether my website validates by running a perl script called validate on every .html file under a particular folder
Code:

for page in $(find /home/andy/save/src/htdocs -name "*.html")
do validate "$page" &>/dev/null || echo "$page is not valid html"
done

This find command changes the permissions on only the files (not the folders) under a particular folder
Code:

find /usr/share/AbiSuite-2.4 -type f -exec chmod 644 {} \;

Locura 09-02-2006 08:17 AM

Thank you both. Andrew, I think I'm on the right track. I'm using the following for statement to look for .txt files in the current working directory:

for file in $(find ~+ -name "*.txt")

However, I'm still running into problems because files that have spaces in them are being split up.

spirit receiver 09-02-2006 09:03 AM

That's where the following comes in handy, as proposed by cs-cam:
Code:

IFS=$'\n'

Locura 09-02-2006 09:13 AM

D'oh! I had commented out that line. My bad!


All times are GMT -5. The time now is 04:56 PM.