bash script: dir1,dir2,dir3 expansion not working as expected from variable, for picking a random fileTrouble using cd command with “~” or “$HOME” in bash scriptinggsettings not working from within bash functionEnvironment Variable seems to be set yet not workingHow to get BASH to use * wildcard in command?Quotation Mark-InceptionSFTP in a cron jobVariable not stored while executing bash commands via gnome-terminalMoving a bash script to /bin directoryWild card expansion that works on command line but not in a bash scriptHow to pass a regex when finding a directory path in bash?

Minimum distance between holes in inner tube

Can you find x?

What exactly is the 'online' in OLAP and OLTP?

What happens to Cessna electric flaps that are moving when power is lost?

If I wouldn't want to read the story, is writing it still a good idea?

Can there be an UN resolution to remove a country from the UNSC?

What is the origin of Scooby-Doo's name?

How is hair tissue mineral analysis performed?

Dates on degrees don’t make sense – will people care?

Can Ogre clerics use Purify Food and Drink on humanoid characters?

How does a blind passenger not die, if driver becomes unconscious

Java TreeMap.floorKey() equivalent for std::map

What is "industrial ethernet"?

What did River say when she woke from her proto-comatose state?

Trainee keeps missing deadlines for independent learning

Parameterize chained calls to a utility program in Bash

Is it damaging to turn off a small fridge for two days every week?

Why does the Saturn V have standalone inter-stage rings?

Does this Wild Magic result affect the sorcerer or just other creatures?

Suggested order for Amazon Prime Doctor Who series

Should I prioritize my 401k over my student loans?

How would modern naval warfare have to have developed differently for battleships to still be relevant in the 21st century?

Count All Possible Unique Combinations of Letters in a Word

How do I set an alias to a terminal line?



bash script: dir1,dir2,dir3 expansion not working as expected from variable, for picking a random file


Trouble using cd command with “~” or “$HOME” in bash scriptinggsettings not working from within bash functionEnvironment Variable seems to be set yet not workingHow to get BASH to use * wildcard in command?Quotation Mark-InceptionSFTP in a cron jobVariable not stored while executing bash commands via gnome-terminalMoving a bash script to /bin directoryWild card expansion that works on command line but not in a bash scriptHow to pass a regex when finding a directory path in bash?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















I have a problem, with this simple script (pick a random file):



#!/usr/bin/env bash
set -x
srcDir="/home/user/Desktop/wallPapers/dir1,dir2,dir3"
randomFile=$(find "$srcDir" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' $randomFile
set +x


The problem is that while I can type this at the command line (and works perfectly fine):



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg"


Then the bash debugging set-commands (set -x and +x) tells me, that for some reason bash both encloses the directory string with single quotation marks and it also replaces the double quotation marks with single quotation marks?



./script.sh
+ srcDir='/home/user/Desktop/wallPapers/dir1,dir2,dir3'
++ find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type f -iname '"*.jpg"'
find: ‘/home/user/Desktop/wallPapers/dir1,dir2,dir3’: No such file or directory
+ randomFile=
+ printf '[%s]n'
[]
+ set +x


I understand, this is what bash sees, when the script runs:



find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type -iname '*.jpg'


And this causes the "No such file or directory"-message, very very annoying... I do not understand, why it inserts these single quotation marks, I want double quotation marks used instead, just like on the command line... Could anyone please explain, I would be happy for that, thanks!










share|improve this question
























  • It's not "*.jpg" that doesn't happen, it's dir1,dir2,dir3.

    – Charles Duffy
    Jun 5 at 15:47











  • Thank you very much. On second thought: Isn't it both? I also don't think '.jpg' expands correctly (if there wasn't a single quotation mark around '.jpg', which was shown from inside the "set -x" and "set +x"-section, I would agree... But I honestly also do not know why bash encloses the directory and the file inside single quotation mark...

    – Okay Dokey
    Jun 5 at 18:48











  • *.jpg, in find . -iname '*.jpg', is parsed by find, not by bash; it's expected that it not be expanded by the shell -- if it were, find would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed to find; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).

    – Charles Duffy
    Jun 5 at 20:05












  • @Charles Duffy Ok, thank you. I'm not that used to the terminology about syntactic / literal quotes. But it's very helpful of you elaborate, thank you very much (eventually I'll hopefully learn it)...

    – Okay Dokey
    Jun 6 at 15:26

















6















I have a problem, with this simple script (pick a random file):



#!/usr/bin/env bash
set -x
srcDir="/home/user/Desktop/wallPapers/dir1,dir2,dir3"
randomFile=$(find "$srcDir" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' $randomFile
set +x


The problem is that while I can type this at the command line (and works perfectly fine):



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg"


Then the bash debugging set-commands (set -x and +x) tells me, that for some reason bash both encloses the directory string with single quotation marks and it also replaces the double quotation marks with single quotation marks?



./script.sh
+ srcDir='/home/user/Desktop/wallPapers/dir1,dir2,dir3'
++ find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type f -iname '"*.jpg"'
find: ‘/home/user/Desktop/wallPapers/dir1,dir2,dir3’: No such file or directory
+ randomFile=
+ printf '[%s]n'
[]
+ set +x


I understand, this is what bash sees, when the script runs:



find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type -iname '*.jpg'


And this causes the "No such file or directory"-message, very very annoying... I do not understand, why it inserts these single quotation marks, I want double quotation marks used instead, just like on the command line... Could anyone please explain, I would be happy for that, thanks!










share|improve this question
























  • It's not "*.jpg" that doesn't happen, it's dir1,dir2,dir3.

    – Charles Duffy
    Jun 5 at 15:47











  • Thank you very much. On second thought: Isn't it both? I also don't think '.jpg' expands correctly (if there wasn't a single quotation mark around '.jpg', which was shown from inside the "set -x" and "set +x"-section, I would agree... But I honestly also do not know why bash encloses the directory and the file inside single quotation mark...

    – Okay Dokey
    Jun 5 at 18:48











  • *.jpg, in find . -iname '*.jpg', is parsed by find, not by bash; it's expected that it not be expanded by the shell -- if it were, find would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed to find; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).

    – Charles Duffy
    Jun 5 at 20:05












  • @Charles Duffy Ok, thank you. I'm not that used to the terminology about syntactic / literal quotes. But it's very helpful of you elaborate, thank you very much (eventually I'll hopefully learn it)...

    – Okay Dokey
    Jun 6 at 15:26













6












6








6








I have a problem, with this simple script (pick a random file):



#!/usr/bin/env bash
set -x
srcDir="/home/user/Desktop/wallPapers/dir1,dir2,dir3"
randomFile=$(find "$srcDir" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' $randomFile
set +x


The problem is that while I can type this at the command line (and works perfectly fine):



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg"


Then the bash debugging set-commands (set -x and +x) tells me, that for some reason bash both encloses the directory string with single quotation marks and it also replaces the double quotation marks with single quotation marks?



./script.sh
+ srcDir='/home/user/Desktop/wallPapers/dir1,dir2,dir3'
++ find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type f -iname '"*.jpg"'
find: ‘/home/user/Desktop/wallPapers/dir1,dir2,dir3’: No such file or directory
+ randomFile=
+ printf '[%s]n'
[]
+ set +x


I understand, this is what bash sees, when the script runs:



find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type -iname '*.jpg'


And this causes the "No such file or directory"-message, very very annoying... I do not understand, why it inserts these single quotation marks, I want double quotation marks used instead, just like on the command line... Could anyone please explain, I would be happy for that, thanks!










share|improve this question
















I have a problem, with this simple script (pick a random file):



#!/usr/bin/env bash
set -x
srcDir="/home/user/Desktop/wallPapers/dir1,dir2,dir3"
randomFile=$(find "$srcDir" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' $randomFile
set +x


The problem is that while I can type this at the command line (and works perfectly fine):



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg"


Then the bash debugging set-commands (set -x and +x) tells me, that for some reason bash both encloses the directory string with single quotation marks and it also replaces the double quotation marks with single quotation marks?



./script.sh
+ srcDir='/home/user/Desktop/wallPapers/dir1,dir2,dir3'
++ find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type f -iname '"*.jpg"'
find: ‘/home/user/Desktop/wallPapers/dir1,dir2,dir3’: No such file or directory
+ randomFile=
+ printf '[%s]n'
[]
+ set +x


I understand, this is what bash sees, when the script runs:



find '/home/user/Desktop/wallPapers/dir1,dir2,dir3' -type -iname '*.jpg'


And this causes the "No such file or directory"-message, very very annoying... I do not understand, why it inserts these single quotation marks, I want double quotation marks used instead, just like on the command line... Could anyone please explain, I would be happy for that, thanks!







command-line bash scripts






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 5 at 18:44









Charles Duffy

1055




1055










asked Jun 4 at 15:19









Okay DokeyOkay Dokey

6010




6010












  • It's not "*.jpg" that doesn't happen, it's dir1,dir2,dir3.

    – Charles Duffy
    Jun 5 at 15:47











  • Thank you very much. On second thought: Isn't it both? I also don't think '.jpg' expands correctly (if there wasn't a single quotation mark around '.jpg', which was shown from inside the "set -x" and "set +x"-section, I would agree... But I honestly also do not know why bash encloses the directory and the file inside single quotation mark...

    – Okay Dokey
    Jun 5 at 18:48











  • *.jpg, in find . -iname '*.jpg', is parsed by find, not by bash; it's expected that it not be expanded by the shell -- if it were, find would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed to find; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).

    – Charles Duffy
    Jun 5 at 20:05












  • @Charles Duffy Ok, thank you. I'm not that used to the terminology about syntactic / literal quotes. But it's very helpful of you elaborate, thank you very much (eventually I'll hopefully learn it)...

    – Okay Dokey
    Jun 6 at 15:26

















  • It's not "*.jpg" that doesn't happen, it's dir1,dir2,dir3.

    – Charles Duffy
    Jun 5 at 15:47











  • Thank you very much. On second thought: Isn't it both? I also don't think '.jpg' expands correctly (if there wasn't a single quotation mark around '.jpg', which was shown from inside the "set -x" and "set +x"-section, I would agree... But I honestly also do not know why bash encloses the directory and the file inside single quotation mark...

    – Okay Dokey
    Jun 5 at 18:48











  • *.jpg, in find . -iname '*.jpg', is parsed by find, not by bash; it's expected that it not be expanded by the shell -- if it were, find would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed to find; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).

    – Charles Duffy
    Jun 5 at 20:05












  • @Charles Duffy Ok, thank you. I'm not that used to the terminology about syntactic / literal quotes. But it's very helpful of you elaborate, thank you very much (eventually I'll hopefully learn it)...

    – Okay Dokey
    Jun 6 at 15:26
















It's not "*.jpg" that doesn't happen, it's dir1,dir2,dir3.

– Charles Duffy
Jun 5 at 15:47





It's not "*.jpg" that doesn't happen, it's dir1,dir2,dir3.

– Charles Duffy
Jun 5 at 15:47













Thank you very much. On second thought: Isn't it both? I also don't think '.jpg' expands correctly (if there wasn't a single quotation mark around '.jpg', which was shown from inside the "set -x" and "set +x"-section, I would agree... But I honestly also do not know why bash encloses the directory and the file inside single quotation mark...

– Okay Dokey
Jun 5 at 18:48





Thank you very much. On second thought: Isn't it both? I also don't think '.jpg' expands correctly (if there wasn't a single quotation mark around '.jpg', which was shown from inside the "set -x" and "set +x"-section, I would agree... But I honestly also do not know why bash encloses the directory and the file inside single quotation mark...

– Okay Dokey
Jun 5 at 18:48













*.jpg, in find . -iname '*.jpg', is parsed by find, not by bash; it's expected that it not be expanded by the shell -- if it were, find would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed to find; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).

– Charles Duffy
Jun 5 at 20:05






*.jpg, in find . -iname '*.jpg', is parsed by find, not by bash; it's expected that it not be expanded by the shell -- if it were, find would never see it. Thus, having a single layer of syntactic quotes (and no literal quotes) is entirely correct and desired in that case. ("Literal" quotes are quotes that are part of the data, and thus passed to find; "syntactic" quotes are quotes that are part of the shell syntax, and thus consumed by bash itself).

– Charles Duffy
Jun 5 at 20:05














@Charles Duffy Ok, thank you. I'm not that used to the terminology about syntactic / literal quotes. But it's very helpful of you elaborate, thank you very much (eventually I'll hopefully learn it)...

– Okay Dokey
Jun 6 at 15:26





@Charles Duffy Ok, thank you. I'm not that used to the terminology about syntactic / literal quotes. But it's very helpful of you elaborate, thank you very much (eventually I'll hopefully learn it)...

– Okay Dokey
Jun 6 at 15:26










3 Answers
3






active

oldest

votes


















11














Brace expansion doesn't occur within a variable assignment, as explained here:



Why do tilde prefixes expand prior to assignment, but braces don't



In other contexts, the quotes would have prevented brace expansion as well.



Even if you do manage to get srcDir to expand to a list of directories, quoting it again in the find command will cause it to be treated as a single argument instead of 3 separate paths.



Probably the right way to do this in bash is to use an array:



#!/usr/bin/env bash
set -x
srcDir=("/home/user/Desktop/wallPapers/"dir1,dir2,dir3)
randomFile=$(find "$srcDir[@]" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' "$randomFile"
set +x





share|improve this answer

























  • This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

    – Okay Dokey
    Jun 4 at 16:00



















4














As others have already pointed out, the quotes are preventing the brace expansion. You could simplify your script to just:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" | shuf -n 1)"


Or, if your file names can contain newline characters:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"


If you want something that can run on arbitrary directories and file types, try this:



#!/usr/bin/env bash

targetFilePattern="$1"
shift
declare -a targetDirs=("$@")
echo "find $targetDirs[@] -type f -iname '$targetFilePattern' | shuf -n 1"
randomFile=$(find "$targetDirs[@]" -type f -iname "$targetFilePattern" | shuf -n 1)
echo "$randomFile"


You can then run it as:



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3


Or even



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3,'a dir with a space'





share|improve this answer

























  • Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

    – Okay Dokey
    Jun 4 at 15:58











  • @OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

    – terdon
    Jun 4 at 16:03












  • Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

    – Okay Dokey
    Jun 4 at 16:20











  • @OkayDokey see update for how to make it truly not hardcoded.

    – terdon
    Jun 4 at 17:16











  • Very, very nice, thank you very much, this is also (more of) what I was looking for...

    – Okay Dokey
    Jun 5 at 18:50



















3














Brace expansion isnt performed inside double quotes. There is a duplicate question regarding this somewhere. Also, use -printf flag for find, doing command substitution is unnecessary, so you can do this



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -printf '[%f]n' | shuf -n1





share|improve this answer

























  • This breaks in the unlikely case where the file names contain newlines.

    – terdon
    Jun 4 at 15:50











  • Fair point, -print0 is better for those cases

    – Sergiy Kolodyazhnyy
    Jun 4 at 15:52











  • Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

    – Okay Dokey
    Jun 4 at 15:56











  • @OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

    – terdon
    Jun 4 at 16:06











  • @OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

    – Sergiy Kolodyazhnyy
    Jun 4 at 16:13













Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "89"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1148573%2fbash-script-dir1-dir2-dir3-expansion-not-working-as-expected-from-variable-f%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









11














Brace expansion doesn't occur within a variable assignment, as explained here:



Why do tilde prefixes expand prior to assignment, but braces don't



In other contexts, the quotes would have prevented brace expansion as well.



Even if you do manage to get srcDir to expand to a list of directories, quoting it again in the find command will cause it to be treated as a single argument instead of 3 separate paths.



Probably the right way to do this in bash is to use an array:



#!/usr/bin/env bash
set -x
srcDir=("/home/user/Desktop/wallPapers/"dir1,dir2,dir3)
randomFile=$(find "$srcDir[@]" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' "$randomFile"
set +x





share|improve this answer

























  • This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

    – Okay Dokey
    Jun 4 at 16:00
















11














Brace expansion doesn't occur within a variable assignment, as explained here:



Why do tilde prefixes expand prior to assignment, but braces don't



In other contexts, the quotes would have prevented brace expansion as well.



Even if you do manage to get srcDir to expand to a list of directories, quoting it again in the find command will cause it to be treated as a single argument instead of 3 separate paths.



Probably the right way to do this in bash is to use an array:



#!/usr/bin/env bash
set -x
srcDir=("/home/user/Desktop/wallPapers/"dir1,dir2,dir3)
randomFile=$(find "$srcDir[@]" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' "$randomFile"
set +x





share|improve this answer

























  • This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

    – Okay Dokey
    Jun 4 at 16:00














11












11








11







Brace expansion doesn't occur within a variable assignment, as explained here:



Why do tilde prefixes expand prior to assignment, but braces don't



In other contexts, the quotes would have prevented brace expansion as well.



Even if you do manage to get srcDir to expand to a list of directories, quoting it again in the find command will cause it to be treated as a single argument instead of 3 separate paths.



Probably the right way to do this in bash is to use an array:



#!/usr/bin/env bash
set -x
srcDir=("/home/user/Desktop/wallPapers/"dir1,dir2,dir3)
randomFile=$(find "$srcDir[@]" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' "$randomFile"
set +x





share|improve this answer















Brace expansion doesn't occur within a variable assignment, as explained here:



Why do tilde prefixes expand prior to assignment, but braces don't



In other contexts, the quotes would have prevented brace expansion as well.



Even if you do manage to get srcDir to expand to a list of directories, quoting it again in the find command will cause it to be treated as a single argument instead of 3 separate paths.



Probably the right way to do this in bash is to use an array:



#!/usr/bin/env bash
set -x
srcDir=("/home/user/Desktop/wallPapers/"dir1,dir2,dir3)
randomFile=$(find "$srcDir[@]" -type f -iname "*.jpg" | shuf -n 1)
printf '[%s]n' "$randomFile"
set +x






share|improve this answer














share|improve this answer



share|improve this answer








edited Jun 4 at 15:44

























answered Jun 4 at 15:39









steeldriversteeldriver

74.2k11122200




74.2k11122200












  • This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

    – Okay Dokey
    Jun 4 at 16:00


















  • This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

    – Okay Dokey
    Jun 4 at 16:00

















This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

– Okay Dokey
Jun 4 at 16:00






This is exactly the solution I was looking for, thank you very much. You keep using the variables, which I wanted to learn how to use. Also, I didn't realise/knew I had to use an array, now I know in the future. In the top of my script I then define "srcDir" - and then the script does whatever it's supposed to do later on, with the result in the "randomFile"-variable. Thank you very much.

– Okay Dokey
Jun 4 at 16:00














4














As others have already pointed out, the quotes are preventing the brace expansion. You could simplify your script to just:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" | shuf -n 1)"


Or, if your file names can contain newline characters:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"


If you want something that can run on arbitrary directories and file types, try this:



#!/usr/bin/env bash

targetFilePattern="$1"
shift
declare -a targetDirs=("$@")
echo "find $targetDirs[@] -type f -iname '$targetFilePattern' | shuf -n 1"
randomFile=$(find "$targetDirs[@]" -type f -iname "$targetFilePattern" | shuf -n 1)
echo "$randomFile"


You can then run it as:



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3


Or even



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3,'a dir with a space'





share|improve this answer

























  • Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

    – Okay Dokey
    Jun 4 at 15:58











  • @OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

    – terdon
    Jun 4 at 16:03












  • Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

    – Okay Dokey
    Jun 4 at 16:20











  • @OkayDokey see update for how to make it truly not hardcoded.

    – terdon
    Jun 4 at 17:16











  • Very, very nice, thank you very much, this is also (more of) what I was looking for...

    – Okay Dokey
    Jun 5 at 18:50
















4














As others have already pointed out, the quotes are preventing the brace expansion. You could simplify your script to just:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" | shuf -n 1)"


Or, if your file names can contain newline characters:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"


If you want something that can run on arbitrary directories and file types, try this:



#!/usr/bin/env bash

targetFilePattern="$1"
shift
declare -a targetDirs=("$@")
echo "find $targetDirs[@] -type f -iname '$targetFilePattern' | shuf -n 1"
randomFile=$(find "$targetDirs[@]" -type f -iname "$targetFilePattern" | shuf -n 1)
echo "$randomFile"


You can then run it as:



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3


Or even



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3,'a dir with a space'





share|improve this answer

























  • Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

    – Okay Dokey
    Jun 4 at 15:58











  • @OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

    – terdon
    Jun 4 at 16:03












  • Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

    – Okay Dokey
    Jun 4 at 16:20











  • @OkayDokey see update for how to make it truly not hardcoded.

    – terdon
    Jun 4 at 17:16











  • Very, very nice, thank you very much, this is also (more of) what I was looking for...

    – Okay Dokey
    Jun 5 at 18:50














4












4








4







As others have already pointed out, the quotes are preventing the brace expansion. You could simplify your script to just:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" | shuf -n 1)"


Or, if your file names can contain newline characters:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"


If you want something that can run on arbitrary directories and file types, try this:



#!/usr/bin/env bash

targetFilePattern="$1"
shift
declare -a targetDirs=("$@")
echo "find $targetDirs[@] -type f -iname '$targetFilePattern' | shuf -n 1"
randomFile=$(find "$targetDirs[@]" -type f -iname "$targetFilePattern" | shuf -n 1)
echo "$randomFile"


You can then run it as:



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3


Or even



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3,'a dir with a space'





share|improve this answer















As others have already pointed out, the quotes are preventing the brace expansion. You could simplify your script to just:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" | shuf -n 1)"


Or, if your file names can contain newline characters:



#!/usr/bin/env bash
printf '[%s]n' "$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"


If you want something that can run on arbitrary directories and file types, try this:



#!/usr/bin/env bash

targetFilePattern="$1"
shift
declare -a targetDirs=("$@")
echo "find $targetDirs[@] -type f -iname '$targetFilePattern' | shuf -n 1"
randomFile=$(find "$targetDirs[@]" -type f -iname "$targetFilePattern" | shuf -n 1)
echo "$randomFile"


You can then run it as:



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3


Or even



printRandomFile '*jpg' /home/terdon/Desktop/wallPapers/dir1,dir2,dir3,'a dir with a space'






share|improve this answer














share|improve this answer



share|improve this answer








edited Jun 4 at 17:15

























answered Jun 4 at 15:46









terdonterdon

70.7k13148231




70.7k13148231












  • Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

    – Okay Dokey
    Jun 4 at 15:58











  • @OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

    – terdon
    Jun 4 at 16:03












  • Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

    – Okay Dokey
    Jun 4 at 16:20











  • @OkayDokey see update for how to make it truly not hardcoded.

    – terdon
    Jun 4 at 17:16











  • Very, very nice, thank you very much, this is also (more of) what I was looking for...

    – Okay Dokey
    Jun 5 at 18:50


















  • Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

    – Okay Dokey
    Jun 4 at 15:58











  • @OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

    – terdon
    Jun 4 at 16:03












  • Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

    – Okay Dokey
    Jun 4 at 16:20











  • @OkayDokey see update for how to make it truly not hardcoded.

    – terdon
    Jun 4 at 17:16











  • Very, very nice, thank you very much, this is also (more of) what I was looking for...

    – Okay Dokey
    Jun 5 at 18:50

















Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

– Okay Dokey
Jun 4 at 15:58





Thanks - also this looks a bit "hardcoded" - I wanted to have the resulting random file-name in a new variable, so I could keep do some manipulation later on in the script. The prinf was only for myself, to see the value. Sorry, you, couldn't know that, because I didn't tell it before... I'm however upvoting for the good explanation, as my way of saying thanks.

– Okay Dokey
Jun 4 at 15:58













@OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

– terdon
Jun 4 at 16:03






@OkayDokey if you want it in a variable, just use randomFile="$(find /home/terdon/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -print0| shuf -zn 1)"

– terdon
Jun 4 at 16:03














Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

– Okay Dokey
Jun 4 at 16:20





Yes, ok, I know. But the path is kind of "hard-coded" which is ok for a small script. But you're right. The solutions you presented are all good, thanks.

– Okay Dokey
Jun 4 at 16:20













@OkayDokey see update for how to make it truly not hardcoded.

– terdon
Jun 4 at 17:16





@OkayDokey see update for how to make it truly not hardcoded.

– terdon
Jun 4 at 17:16













Very, very nice, thank you very much, this is also (more of) what I was looking for...

– Okay Dokey
Jun 5 at 18:50






Very, very nice, thank you very much, this is also (more of) what I was looking for...

– Okay Dokey
Jun 5 at 18:50












3














Brace expansion isnt performed inside double quotes. There is a duplicate question regarding this somewhere. Also, use -printf flag for find, doing command substitution is unnecessary, so you can do this



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -printf '[%f]n' | shuf -n1





share|improve this answer

























  • This breaks in the unlikely case where the file names contain newlines.

    – terdon
    Jun 4 at 15:50











  • Fair point, -print0 is better for those cases

    – Sergiy Kolodyazhnyy
    Jun 4 at 15:52











  • Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

    – Okay Dokey
    Jun 4 at 15:56











  • @OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

    – terdon
    Jun 4 at 16:06











  • @OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

    – Sergiy Kolodyazhnyy
    Jun 4 at 16:13















3














Brace expansion isnt performed inside double quotes. There is a duplicate question regarding this somewhere. Also, use -printf flag for find, doing command substitution is unnecessary, so you can do this



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -printf '[%f]n' | shuf -n1





share|improve this answer

























  • This breaks in the unlikely case where the file names contain newlines.

    – terdon
    Jun 4 at 15:50











  • Fair point, -print0 is better for those cases

    – Sergiy Kolodyazhnyy
    Jun 4 at 15:52











  • Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

    – Okay Dokey
    Jun 4 at 15:56











  • @OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

    – terdon
    Jun 4 at 16:06











  • @OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

    – Sergiy Kolodyazhnyy
    Jun 4 at 16:13













3












3








3







Brace expansion isnt performed inside double quotes. There is a duplicate question regarding this somewhere. Also, use -printf flag for find, doing command substitution is unnecessary, so you can do this



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -printf '[%f]n' | shuf -n1





share|improve this answer















Brace expansion isnt performed inside double quotes. There is a duplicate question regarding this somewhere. Also, use -printf flag for find, doing command substitution is unnecessary, so you can do this



find /home/user/Desktop/wallPapers/dir1,dir2,dir3 -type f -iname "*.jpg" -printf '[%f]n' | shuf -n1






share|improve this answer














share|improve this answer



share|improve this answer








edited Jun 4 at 15:49









terdon

70.7k13148231




70.7k13148231










answered Jun 4 at 15:39









Sergiy KolodyazhnyySergiy Kolodyazhnyy

76.9k10162340




76.9k10162340












  • This breaks in the unlikely case where the file names contain newlines.

    – terdon
    Jun 4 at 15:50











  • Fair point, -print0 is better for those cases

    – Sergiy Kolodyazhnyy
    Jun 4 at 15:52











  • Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

    – Okay Dokey
    Jun 4 at 15:56











  • @OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

    – terdon
    Jun 4 at 16:06











  • @OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

    – Sergiy Kolodyazhnyy
    Jun 4 at 16:13

















  • This breaks in the unlikely case where the file names contain newlines.

    – terdon
    Jun 4 at 15:50











  • Fair point, -print0 is better for those cases

    – Sergiy Kolodyazhnyy
    Jun 4 at 15:52











  • Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

    – Okay Dokey
    Jun 4 at 15:56











  • @OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

    – terdon
    Jun 4 at 16:06











  • @OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

    – Sergiy Kolodyazhnyy
    Jun 4 at 16:13
















This breaks in the unlikely case where the file names contain newlines.

– terdon
Jun 4 at 15:50





This breaks in the unlikely case where the file names contain newlines.

– terdon
Jun 4 at 15:50













Fair point, -print0 is better for those cases

– Sergiy Kolodyazhnyy
Jun 4 at 15:52





Fair point, -print0 is better for those cases

– Sergiy Kolodyazhnyy
Jun 4 at 15:52













Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

– Okay Dokey
Jun 4 at 15:56





Thank you very much, but for a script that could eventually become bigger I prefer executing some kind of expression, based on variables, defined in the top of the script. This looks a bit more like something on the command line - but I upvoted, due to the explanation. The purpose of my script was also not to just print something out on the screen (the printf-line) - but to do some further manipulation. I know you couldn't see that from my original post, so sorry about that... And thanks.

– Okay Dokey
Jun 4 at 15:56













@OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

– terdon
Jun 4 at 16:06





@OkayDokey you seem to be misunderstanding. This (and all other answers so far) are no more "hardcoded" than your approach. But perhaps we can give you better solutions if you edit your question and explain in more detail.

– terdon
Jun 4 at 16:06













@OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

– Sergiy Kolodyazhnyy
Jun 4 at 16:13





@OkayDokey If you do need to use dir1,dir2,dir3 later in a script, use set command or array to save the directory names. I would explain further but currently have no time. And yes, it was not obvious that you want to reuse those further.

– Sergiy Kolodyazhnyy
Jun 4 at 16:13

















draft saved

draft discarded
















































Thanks for contributing an answer to Ask Ubuntu!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1148573%2fbash-script-dir1-dir2-dir3-expansion-not-working-as-expected-from-variable-f%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company