Colan Biemer
Colan Biemer

Reputation: 9

Entering directory through unix bash script issue

Be aware that this code i'm about to post is purposefully not perfect and will not work should there be a a text file in the directory but the full code does have such a check. But the issue is that this:

#!/bin/bash 
for d in *; do 
    cd $d 
done 

produces:

./test: line 3: cd: 500: No such file or directory 
./test: line 3: cd: 536: No such file or directory 
./test: line 3: cd: 560: No such file or directory 
./test: line 3: cd: 572: No such file or directory 
./test: line 3: cd: out.txt: No such file or directory 
./test: line 3: cd: prob1: No such file or directory 
./test: line 3: cd: problem2: No such file or directory 
./test: line 3: cd: README: No such file or directory 
./test: line 3: cd: test: No such file or directory 

where 500, 536, 560, and 572 are directories that should be able to be opened. If I do just a cd 500 then I can go into the directory without an issue. But it will not work when I use the automated process in the shell script.

alright so after further going into the program i now have:


#!/bin/bash
cd "$1"
for d in */; do
    (
         cd "$d"
        for file in $*; do
        (
                bla="$(head -4 $file|tail -1)"
                cd ~cfb43/cs265/a1
                echo $bla > out.txt
                cd
                cd "$1"
                cd "$d"
        )
        done
        cd "$1"
    )
done

and i receive:


head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory
head: error reading `/home/cfb43/cs265/a1': Is a directory

All i want to do is go into a directory and read from a file and get the fourth line of text and print it to out.txt in my folder. I'm not sure why this code is getting stuck at a1 and not atleast 500 or something like that. any further help and i would be very greatful

Upvotes: 1

Views: 1227

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19335

are you sure of what you are doing: $* which expands to parameters $1 $2 .. ${!#}

for file in $*; do

maybe you want: * which expands to files in current directory

for file in *; do

Another way to do is to never change directory:

for file in */*;do
   head -4 "$file" | tail -1 >> ~cfb43/cs265/a1/out.txt
done

and another way to do

head -4 | tail -1

with sed

sed n '4{p;q}'

with awk

awk 'NR==4{print;exit}'

with perl

perl -ne 'if($.==4){print;exit}'

Upvotes: 1

user000001
user000001

Reputation: 33387

Because you try to enter the next subdirectory without leaving the previous one. You could do

#!/bin/bash 
for d in */; do 
    cd -- "$d"
    # do some stuff
    cd .. 
done 

or use a subshell

#!/bin/bash 
for d in */; do 
    (
        cd -- "$d"
        # do some stuff
    )
done 

Upvotes: 5

Related Questions