0

I am trying to take a filename from the ~/Pictures folder and supply it as an argument for the nomacs command. The filename contains some spaces, so I am using Bash substitution to escape spaces (I also want to take last file in the folder).

The code:

names=$(\ls ~/Pictures * | tac) 
SAVEIFS=$IFS
IFS=$'\n'
names=($names)
IFS=$SAVEIFS
screenshot=~/Pictures/${names[0]}
screenshot=${screenshot// /\\ }
nomacs $screenshot

Example of the filename: Screenshot from 2017-09-13 18-05-42.png

The problem is that nomacs $screenshot does not work but when I execute nomacs Screenshot\ from\ 2017-09-13 18-05-42.png, it works as expected.

Should I use some special Bash technique for escaping spaces?

4
  • 1
    It is generally a really bad idea to parse the output of ls. You should probably look into either using find or simple shell globbing to get your list of files to process. Extensive further reading on the subject can be found here. Further, what specifically do you mean by 'last' file in the directory? Most recent? Last lexically? Last in character sort order? Last modified? What if this 'last' file is a directory?
    – DopeGhoti
    Sep 13, 2017 at 16:33
  • if you're using ls to get the most recent or oldest file, there are also other Q's on here for doing that in various shells
    – Jeff Schaller
    Sep 13, 2017 at 16:34
  • Then you're still parsing ls, which is a bad idea that should make you feel bad.
    – DopeGhoti
    Sep 13, 2017 at 16:36
  • 2
    Did you mean to say ls ~/Pictures/* there? Otherwise you're getting an ls of ~/Pictures and of *
    – Jeff Schaller
    Sep 13, 2017 at 16:39

1 Answer 1

2

From what I gather from your script, you're reversing the output of ls and selecting the first item. Here's a different way to do that with bash:

files=(~/Pictures/*)
nomacs "${files[-1]}"

This fills an array with the glob expansion of ~/Pictures/* then passes the last element to the nomacs program.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .