BASH: Assigning a string containing pipes to a variable
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Notice the different ways I played with your argument passing, they all work, the '\'' method is the safest thing when you want to embed single quotes in single-quoted text the shell's going to see again, because it doesn't change the way the shell treats the contents the shell's going to see on the rescan.
root@debian-pc1:~# bash -x scripts/script.bsh
+ PATTERN='rpm\|drpm\|install.img'
scripts/script.bsh: line 9: unexpected EOF while looking for matching `''
scripts/script.bsh: line 11: syntax error: unexpected end of file
My fault on the tr arg, put a space between the -s and the backslash. Using '\'' outside a single-quoted string fails, as you discovered.
The '\'' '\'' generates a backslash (the text between the first pair of single quotes), a space (between the second pair), a single quote (because that one is escaped by the second backslash), and the last single quote starts a string the shell runs off the end of the script looking for the end of, producing the complaints you saw.
Well maybe if you explained what you were trying to accomplish we could help. I say this as to process ls is a bad idea as you can read about here.
If you need an example of why this is a bad idea, simply doing an ls -l in my home directory I have no lines with 9 fields so your cut would not work as expected.
I want to assign the following section to a variable, for later reference and/or modification:
....
How can I do this?
Thanks.
The simple answer is...you don't! Variables are designed for containing data, not code. Pipes and redirections in particular cannot be handled this way except through the use of eval, and eval has security implications.
If you want a way store a command dynamically then you should use a function. That's what they were designed for.
Second, as grail pointed out, don't parse ls for filenames. Use a globbing pattern or find; and store the results in an array if you need to process the entries more than once or in an arbitrary order.
And again, if you would explain exactly what your actual goal is, and give us some examples of the input and desired output, we'll be glad to help you find a more workable solution.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.