Bash script: issue changing directories in script


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Bash script: issue changing directories in script
# 1  
Old 05-24-2009
Bash script: issue changing directories in script

I am working on a script that checks two arguments at the command line. The first argument is a search pattern, the second can be a file or a directory, if it is a file a second script is called that checks it for the search pattern. If the second argument is a directory, it checks for the search pattern in all files in the that directory.
The script works ok if the second argument is a sub-directory of the working directory of the script. The issue occurs when the script needs to change directories. I don't think it likes the "/" if I specify a directory, but i'm stuck as far figuring out what to do next.

Here is the snippet of code I am having the trouble with:
Code:
elif [ -d $2 ]   #test the command line argument for a directory
then
#change directories to the the second command line argument
        cd $2
        filename=`ls -l | cut -c59-78`
        for entry in $filename
        do
        # Verify that the name read in the directory is a file
                if [ -f $filename ]
                then
        # Search the files for the pattern specified by $1, then call search.sh
            ./search.sh $1 $listing

# 2  
Old 05-24-2009
Hi

Instead of writing -- ls -l | cut -c59-78 this might not give you the correct file name.

write : ls -l | awk '{print $NF}' to pull the file name.

-if you will provide a "directory name" as argument - It will by default look into your current directory as subdirectory only. and can't intelligently cd to the directory you are expecting.

-You can provide full path name in the argument so that the cd will work properly if it is directory else if it will be a file you can search on it.
# 3  
Old 05-24-2009
Thanks, I will try it with the awk statement and see what I get.

Something I left out the first time, the script returns the error
"[: ash: unexpected operator/operand" when I try to use the full path of a directory.

Thanks again.
# 4  
Old 05-24-2009
first off: you don't need the "cd" statement at all. And secondly, you should NEVER EVER iterate through an unknown directory with a for-loop: if the number of directory entries becomes higher you will execeed the maximum command line length and your script will fail. write it the following way:

Code:
ls ${2}/* | while read filename ; do
     do_something "$filename"
done

Another problem is the "./search.sh" you mention at the end of your code snippet. You know that you are in some arbitrary directory and not the one you have started the script in, yes?

I hope this helps.

bakunin
# 5  
Old 05-24-2009
You may be safer with ls -1 (ls hyphen one) which just lists the names for the files, then pipe to a "while read". This is in case you have filenames containing space characters which will break the "for" statement or you have so many files that the "for" statement becomes too long.
You have an issue with $entry which is not referred to at all and is probably surplus.
It would also be better to place $2 in to a named variable for readability.
Notice how we put double quotes round any parameter (including filenames) to preserve any embedded space characters.

I like your use of comment lines. Very good.



Code:
elif [ -d "${2}" ]   #test the command line argument for a directory
then
#change directories to the the second command line argument
        cd "${2}"
        ls -1 | while read filename
        do
        # Verify that the name read in the directory is a file
                if [ -f "${filename}" ]
                then
        # Search the files for the pattern specified by $1, then call search.sh
            ./search.sh "${1}" "${listing}"

Bump: bakunin has made a valid point. The cd could cause the "./search" statement to fail unless the script called "search" existed in that directory.

At the start if the script (or in your .profile) you can change $PATH to ensure that you find your scripts.

Let's say that your scripts are in directory /home/Breakology/scripts .
If we want to refer to our scripts by name we can adjust the PATH.

Code:
PATH=${PATH}:/home/Breakology/scripts
export PATH

The script called "search" can then be called as "search" not "./search".

Addition Information Added:

(I have absolutely no idea where the "bump" came from and I am sending this post to test a theory).
# 6  
Old 05-26-2009
Thanks guys, I am re-writing the script using your suggestions. My original problem was a syntax error, I was [ -f filename ] the wrong variable and thats why I got the errors.
I am glad I posted it here because of the good suggestions I received. I am starting to catch on, there is just A LOT to learn. Thanks again.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Changing date using bash script

I am trying to change dates in a bash script. I have a start time and an endtime and want to increment the times. Basically the month and day have to be incremented in a loop to create two strings, stm and etm defining the start and end times. stm="2014-05-13T00:00:00"... (4 Replies)
Discussion started by: novilatte
4 Replies

2. UNIX for Beginners Questions & Answers

Connecting and changing variables in Bash script

#!/bin/bash X=$(</home/cogiz/computerhand.txt) # (3S 8C 2H 6D QC 8S 4H 5H) Y=$(</home/cogiz/topcardinplay.txt) # KS A=( "${Y::1}" ) B=( "${Y:1}" ) for e in ${X}; do if ]; then # searching for valid cards K,S or 8 ... (0 Replies)
Discussion started by: cogiz
0 Replies

3. Shell Programming and Scripting

Changing script from csh to bash

Hello Guys I have a script working fine on csh, but I would like to change it to bash, how I should change this command to be able to work as bash script. :wall: if ( $fsw > "0" ) then foreach swath ( `awk 'BEGIN {for (i='$fsw';i<='$lsw';i++) printf ("%s\n", i) }'` ) ## work to be done... (2 Replies)
Discussion started by: jiam912
2 Replies

4. Shell Programming and Scripting

Chose list of sub directories in a bash script file

Hi, I have a command in my bash script, searchDirectoryName.sh: DIR_NAME=$(find . -type d) echo "${DIR_NAME}" . ./Dir1 ./Dir1/1.0.2.1 ./Dir2 ./Dir2/1.1 ./Dir3 ./Dir3/2.2.1 How can I select only following directory names with second subdirectoies and without first ./ in the... (3 Replies)
Discussion started by: hce
3 Replies

5. Shell Programming and Scripting

changing cron using bash script

How can I change the cron entries only for ABC and XYZ from dosomething_1.0.sh to nowchanged_2.0 using a bash script ? Any help will be appreciated. # # ABC 00,05,10,15,20,25,30,35,40,45,50,55 * * * * /mydir/dosomething_1.0.sh 1>/dev/null 2>&1 # # ## # DEF... (4 Replies)
Discussion started by: jville
4 Replies

6. Shell Programming and Scripting

Changing File Time Stamp (Bash Script)

I need some help recovering from a "slight" screwup. We just moved 3 TB of data from one RAID Array to another. Low lever archive files. This was done with a regular cp (for some reason) and now we have lost all the timestamps on the files, and we urgently need to get the timestamps back on these... (7 Replies)
Discussion started by: chj
7 Replies

7. Shell Programming and Scripting

bash script to rename multiple directories

Hello I have a directory structure with year in format 4 digits, e.g 2009, below which is month format 1 or 2 digits, e.g 1 or 12, blow which is day format 1 or 2 digits, e.g 1 or 31. I want to change the names of lots of directories to the be Year - 4 digits , e.g 2009 - No change here... (4 Replies)
Discussion started by: garethsays
4 Replies

8. Shell Programming and Scripting

Bash Script to Read & Write on different directories

Hi, root@server] df -h 121G 14G 101G 12% /home 147G 126G 14G 91% /backup We having our site files and images are storing in /backup/home/user/files/ through symbolic link created in /home directory pointing in /backup directory as following. root@server] cd /home... (1 Reply)
Discussion started by: mirfan
1 Replies

9. Shell Programming and Scripting

(w)get web server's directories + bash script

Hi everyone. I need to write a script which will download files/folders (a huge collection) to the local file server (centOS 4.4 Server), and check regularly (every 6 hours or so if any new files are present, or if the old ones were modified to update contents). Any insights on how to tackle... (2 Replies)
Discussion started by: reminiscent
2 Replies

10. Shell Programming and Scripting

Bash Script to display directories in Path?

Hello there, As a newbie: The directories in PATH can be hard to distinguish when printed out as one line with colon .Please, can i have a sample script to display them,one to a line. Thank you. (1 Reply)
Discussion started by: debut
1 Replies
Login or Register to Ask a Question