简体   繁体   中英

Variable Corruption in bash script

Given the following code I am expecting the variable $NewFile to be /var/ftp/pub/faxes/myfile.txt.pdf
However my system is returning: ".pdf/ftp/pub/faxes/myfile.txt"

$Ext returns: "txt"
$oFileName returns: "/var/ftp/pub/faxes/myfile.txt"

I have tried this a hundred different ways with no luck.

PDF=".pdf"

#extract the file.ext from the script
FileName1=`head $f -n1 | awk -F/ '{print $NF}' | sed 's/\"//'`
FileName2=`head $f -n1 | awk -F/ '{print $NF}' | sed 's/\"//'`
FileName3=`head $f -n1 | awk -F/ '{print $NF}' | sed 's/\"//'`

FileName=`basename $FileName1`
Ext=`echo $FileName | awk -F . '{print $NF}'`

FileName=`basename $FileName2`
oFileName=/var/ftp/pub/faxes/${FileName}

FileName=`basename $FileName3`
NewFile=/var/ftp/pub/faxes/${FileName}${PDF}

echo $oFileName
echo $NewFile
echo $Ext

Any help is appreciated.

Comment: if you ever move to a normal Unix-like system instead of Linux, you won't get away with ' head $f -n1 '; you must put option (control) arguments before file names, so use ' head -n1 $f '. (If you set environment variable POSIXLY_CORRECT, Linux will behave the same as other systems.)

Comment: you could perfectly well write:

FileName1=`head -n1 $f | awk -F/ '{print $NF}' | sed 's/\"//'`
FileName2=$Filename1
FileName3=$Filename1

It makes more sense than running the same three programs on the same data three times.

Comment: you should learn and use the '$(...)' notation:

FileName1=$(head -n1 $f | awk -F/ '{print $NF}' | sed 's/\"//')

When run on MacOS X, with f=xxxx.input and the file xxxx.input containing one line that says '/some/where/myfile.txt', the script produces:

/var/ftp/pub/faxes/myfile.txt
/var/ftp/pub/faxes/myfile.txt.pdf
txt

The trace output ('bash -x') is:

+ f=xxxx.input
+ PDF=.pdf
++ head -n 1 xxxx.input
++ sed 's/\"//'
++ awk -F/ '{print $NF}'
+ FileName1=myfile.txt
++ head -n 1 xxxx.input
++ awk -F/ '{print $NF}'
++ sed 's/\"//'
+ FileName2=myfile.txt
++ awk -F/ '{print $NF}'
++ head -n 1 xxxx.input
++ sed 's/\"//'
+ FileName3=myfile.txt
++ basename myfile.txt
+ FileName=myfile.txt
++ echo myfile.txt
++ awk -F . '{print $NF}'
+ Ext=txt
++ basename myfile.txt
+ FileName=myfile.txt
+ oFileName=/var/ftp/pub/faxes/myfile.txt
++ basename myfile.txt
+ FileName=myfile.txt
+ NewFile=/var/ftp/pub/faxes/myfile.txt.pdf
+ echo /var/ftp/pub/faxes/myfile.txt
/var/ftp/pub/faxes/myfile.txt
+ echo /var/ftp/pub/faxes/myfile.txt.pdf
/var/ftp/pub/faxes/myfile.txt.pdf
+ echo txt
txt

You will need to show what you're really using, and 'bash -x' may well help you see where your problem is -- I cannot reproduce it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM