shell - cd doesn't work in bash while read loop -
i'm writing simple script cd multiple folders file, cd doesn't work.
i have tried solutions in why doesn't "cd" work in bash shell script? , shell script change directory variable
but didn't work.
here script:
cat filename.txt | while read line; echo $line line=$(echo $line | tr -d '\r') cd "$line" done + inputfile=drugs800folders.txt + ifs= + read -r line + line=cid000000923 + cd cid000000923 + awk '$11 < 0.05 {print $1 $2 $3 $8 $10 $12}' groups.txt + ifs= + read -r line + line=cid000001003 + cd cid000001003 filterfuncoutput.sh: line 5: cd: cid000001003: no such file or directory + exit
@charles duffy works, , did awk first folder in list, not remaining folders after first line first line selects first file in list ?
unless have lastpipe
shell option set (and prerequisites operation met), elements of shell pipeline in bash run in own subshell. consequently, side effects of pipeline components on shell's state thrown away when subshell exits.
furthermore, edits , comments have made clear don't want each cd
take place after other (thus, net effect being equivalent cd line1dir/line2dir/line3dir/line4dir
), relative starting directory. in future, make constraints of kind clear in initial question.
fortunately, don't need pipeline here @ all:
#!/bin/bash inputfile=${1:-filename.txt} owd=$pwd # store original directory while ifs= read -r line; line=${line%$'\r'} # remove trailing cr if exists cd "$owd/$line" || continue echo "now in directory $pwd" done <"$inputfile"
now, let's @ specific things differently:
- the
cat
call (and pipeline output, resulted incd
having no continued effect after loop exited) gone. - clearing ifs allows names ending in whitespace passed through unmodified.
- using
-r
argumentread
prevents names literal backslashes being munged. - using
|| exit
oncd
line ensures script won't continue operate wrong directory in event of failure. - the
echo $line
gone. it's not accurate debugging measure begin with; if want see script doing, runbash -x yourscript
or addset -x
line.
bashfaq #24 goes detail respect root cause here.
Comments
Post a Comment