3

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 .

1 Answer 1

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.