Search code examples
bashvariablesfilenamesfastq

Opening File with backslash in name, using a variable in bash


A complicated name for a simple question. I am trying to make an idiot proof program for people I work with when I am gone. I am using read to save a file name as a variable. When I drag and drop a file from a fold who's name has a space (and hence a backslash) it won't work. If I type the name straight in it works. Examples below.

$ read -re a
/Users/microuser/Desktop/han\ scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq 
$ echo $a
/Users/microuser/Desktop/han\ scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq
$ echo "$a"
/Users/microuser/Desktop/han\ scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq
$ head $a
head: /Users/microuser/Desktop/han\: No such file or directory
head: scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq: No such file or directory
$ head "$a"
head: /Users/microuser/Desktop/han\ scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq: No such file or directory

however if I type it in instead of using a variable.

$ head -n 1 /Users/microuser/Desktop/han\ scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq 
@HWI-ST1280:209:D2GDVACXX:8:1101:2762:1973 1:Y:0:GATCAGA

if I take the space out of the folder name using the variable works fine.


Solution

  • You don't need to put backslash before space while reading the input and avoid using -r option as -r option says do not allow backslashes to escape any characters.

    This should work:

    $ read -e a
    /Users/microuser/Desktop/han scans/D2GDVACXX_s8_0_7bp_Index_9_SL39794.fastq 
    $ head "$a"