2

I am using a script to copy some files depending on the year they were created in, it works fine with files without spaces but with the files with spaces there is a problem with the stats command,for example i have this file : file with spaces.pdf

stat -c %y ./path/to/file\ with\ spaces.pdf|cut -d '-' -f 1

returns the year , for example :2017

but when used inside a script :

year=$(stat -c %y $pathfile | cut -d '-' -f 1)

it does not seem the work , and if i took the output of :

 echo "stat -c %y file | cut -d '-' -f 1"

and copy past it in a terminal it does work,the error is the same in all the cases, it's like ignoring this part of the file name :with\ spaces.pdf:

stat: cannot stat './path/to/file\': No such file or directory

I've tried adding quotes to the path,and it does not seem to work:

year=$(stat -c %y "$pathfile" | cut -d '-' -f 1)

I've seen somewhere that i need to place the stats in a function ,which i did:

 makestats () {
 $(stat -c %y $1|cut -d '-' -f 1)
 }

but it does not seem to work, i get the same error if you can give me your help that would be great .

6

Quote your variables in bash, not doing them will split your words in the variable to individual tokens and the command that uses that variable will be getting multiple words when it was expected a single string (See Word Splitting in shell)

year=$(stat -c %y "$pathfile" | cut -d '-' -f1)

I suppose your problem is in your variable you are using " along with the \ escape sequence. You need to do either of the one.

pathfile="/path/to/file with spaces"
  • I've tried this solution and it does not seem to work – Kingofkech Oct 4 '17 at 13:42
  • @Kingofkech: it should work! What errors are you seeing with this? – Inian Oct 4 '17 at 13:44
  • The same error : stat: cannot stat './path/to/file\': No such file or directory it's ignoring the second part :/ – Kingofkech Oct 4 '17 at 13:45
  • 1
    @Kingofkech use either quotes ( " ) or backslash ( \ ), but not both. – Archemar Oct 4 '17 at 13:48
  • 1
    @Kingofkech: That is the problem! See my update! – Inian Oct 4 '17 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.