find cannot do on having space within string variable for -path or -iregex or etc

Unix & Linux Asked by nonox on November 26, 2020

Cannot have space within string variable for -path or -iregex find’s option.
This input '/home/demo.*/.config/File System/.*t$'
is fed on:

read i

m="-iregex $i"
find ~ $m

won’t work as it will if constant, not variable
so is not find ~ '$m' nor eval find ~ '$m'
How’s the correct solution ?

One Answer

Don't put actions into a string variable that contains the data (see Bash FAQ 50). And always double-quote your variables when you use them

i='/home/demo.*/.config/File System/.*t$'
find ~ -iregex "$i"

If you want to include the -iregex only if $i is not empty then you can do something like this, which keeps it but replaces the regular expression with .* (i.e. anything)

find ~ -iregex "${i-.*}"

If you are using a shell such as bash (but not sh) that understands arrays you can use one to include the -iregex only if needed

IFS= read -r i

[[ -n "$i" ]] && findRegex=('-iregex' "$i")

find ~ "${findRegex[@]}"

To see what's going on here you can modify find to echo find. Reading man bash and searching for Arrays and/or @ may also help.

Notice I've also changed your read i to IFS= read -r i. This stops the shell trying to parse your input data, which can break expressions containing multiple spaces (characters in $IFS to be precise) and other character combinations

Correct answer by roaima on November 26, 2020

Add your own answers!

Related Questions

How to upgrade rhel 7.2 to rhel 7.6 Server

0  Asked on February 10, 2021


Is there a way to reset updates on Debian (with apt)?

0  Asked on February 10, 2021 by coffeecatde


How to use GoToMeeting in Linux

4  Asked on February 8, 2021 by illarion-kovalchuk


How to activate v-sync with nvidia linux driver?

1  Asked on February 7, 2021 by chiseledabs


How to set country (region) for WiFi globally in Linux Mint 20?

1  Asked on February 6, 2021 by linuxsecurityfreak


lsblk doesn’t show attached virtual storage / partition

1  Asked on February 5, 2021 by robert-einsle


Samba with multiple shares from the same server

3  Asked on February 5, 2021 by s55michi


increase TrackPoint sensitivity beyond max

0  Asked on February 5, 2021 by modernneo


Can GRUB font size be customised?

5  Asked on February 5, 2021 by neydroydrec


Ubuntu route table: docker entry causes VPN to not resolver

1  Asked on February 5, 2021 by perimosh


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir