0

If I write:

ls -i '/home/user/Desktop/file' | awk '{print $1}'

I get the inode number of the specified file.

I want to make a script that gives me back the inode number of a certain file.

If I do:

read file
'/home/user/Desktop/file2'

and then:

ls -i "$file" | awk '{print $1}'

It returns that ls cannot find '/home/user/Desktop/file2'.

why? thanks

muru
  • 72,889
  • Based on your post I'm not sure why you're using "read file". Are you trying to grab a filename from file2? Or do you mean:
    $FILE="/home/user/Desktop/file2"
    ls -i $FILE | awk '{ print $1 }'
    
    – kevlinux Dec 11 '18 at 04:54
  • after the read command I drag the file from desktop to terminal and it prints on shell the file path. terminal returns: ls: cannot access "'/home/user/Desktop/file2'": No such file or directory – pietro letti Dec 11 '18 at 04:56
  • Yeah, after reading muru's post below I understand what you're doing now. Totally not what I was imagining. – kevlinux Dec 11 '18 at 06:34

1 Answers1

1

In ls -i '/home/user/Desktop/file', the shell removes the quotes around /home/user/Desktop/file before passing it to ls. ls gets /home/user/Desktop/file as the argument.

When you input '/home/user/Desktop/file2' to read file, those quotes are retained in the variable. Then, in ls "$file", bash expands the variable, and removes the quotes which are not a result of variable expansion (so the "..." which were originally present in the command, but not the '...' from the variable's contents). ls gets '/home/user/Desktop/file2' as the argument, and of course, there's no such file.

You don't need to additionally have quotes inside a variable. If you want to enter a filename (including spaces and backslashes, etc.) more safely using read, use this instead:

IFS= read -r file

And as the input:

/home/user/Desktop/file2
muru
  • 72,889
  • when I drag a file into terminal by default it prints quotes at the beginning and at the end of the path dragged in. I tried to remove them with sed or tr command but it didn't work. How can I remove quotes when I drag files in terminal? [if I manually write the full path without quotes the script works] – pietro letti Dec 11 '18 at 05:20
  • 1
    You can try something like file="$(eval "printf %s $file")" or file="$(sh -c "printf %s $file")" - I think whatever does the quoting does it relatively safely for use in a shell command line, so if we use it as a part of a command for a new shell, or using eval, the quotes can be parsed out. – muru Dec 11 '18 at 05:34
  • thanks. file="$(eval "printf %s $file")" works. – pietro letti Dec 11 '18 at 05:38
  • 1
    Hmm, eval file="$file" might be simpler. – muru Dec 11 '18 at 05:39