6

So the script is:

#!/bin/bash

for line in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
   if [[ "$line" = "" || "$line" = " " ]]; then
      exit
   else
      unzip "$line" -d "temp"
   fi
done

It works well and unzips the file. But if the file is named with a space (eg: Leon - 1994.zip) it will not work and the $line will be

1st time: /home/citybong/Downloads/Leon

2nd time: -

3rd time: 1994.zip

Edit: I fount a link http://g-scripts.sourceforge.net/faq.php for the question: "My script can't handle multiple files/files with spaces" but i am kinda newbie to bash scripting and i can't understand their solutions

Leon Vitanos
  • 1,212
  • 4
  • 14
  • 24

4 Answers4

10

IFS is by default set to space, that's why your string is being divided into spaces. Just set it to the newline with the following code:

IFS_BAK=$IFS
IFS="
"

for line in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
    whatever $line
done

IFS=$IFS_BAK
hytromo
  • 4,904
  • 3
  • 33
  • 63
5

You don't need to mess with IFS:

echo "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | while read filename; do
    unzip "$filename" -d temp
done

I had a similar problem and it turns out that echo preserves newlines in double quotes, but without quotes changes them to spaces.

Janek37
  • 51
  • 2
0

Using $@ instead of $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS in Nautilus scripts could solve the problem with new line separators (which are used as delimiters in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS and $NAUTILUS_SCRIPT_SELECTED_URIS).

So, the code will look like:

#!/bin/bash

for line in "$@"; do
   if [[ "$line" = "" || "$line" = " " ]]; then
      exit
   else
      unzip "$line" -d "temp"
   fi
done

Also, this is handy when we need just pass selection to another app:

#!/bin/sh

baobab "$@"
dess
  • 682
  • 1
  • 8
  • 16
-2

Put single quotes around the variable name, like so:

#!/bin/bash

for line in '$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'; do
   if [[ "$line" = "" || "$line" = " " ]]; then
      exit
   else
      unzip "$line" -d "temp"
   fi
done
Clive van Hilten
  • 1,574
  • 12
  • 13