Send 2 parameters to a script

2019-09-08 16:09发布

问题:

I just started using bash so I hope the answer is not obvious. I have a file called playlists.txt that looks like this:

  • ChilledDubstep PLYNrAD9Jn2WDwRrS_Uw6UR55K-c_s6EH4
  • Classical PLYNrAD9Jn2WDWZFpIG3a2tkOBtdeNAbc6
  • ChilledOut PLYNrAD9Jn2WCfrUCoS22kn3pBX1XUFinE
  • SlickSlickSound PLYNrAD9Jn2WDmpu3gNVxIVO8bAiOcQkx7
  • Albums,concerts PLYNrAD9Jn2WD3BI8o5VjmSbhZgfYh5zaX

I want to assign the first string of each line to $name and the second string to $hash, then send it to script.sh and do this recursively for every line, knowing that the number of lines might increase in the future.

I wrote this but it does not work: using this ->How to split one string into multiple variables in bash shell?

while read name hash
do

        sh script.sh "$name" "$hash"

done < playlists.txt

Whats should I be doing instead? Thank you in advance.

EDIT: Thanks guys, so I changed it to this, it is easier to read. I thought, it was going to resolve my errors, but there are still there...damn it. So basically, in script.sh, here is the first part:

cd ~/Music/Youtube\ Playlist/Playlists/$name

mv $HOME/Music/Youtube\ Playlist/Playlists/$name/TextRecords/lastoutput.txt $HOME/Music/Youtube\ Playlist/Playlists/lastoutput.txt

However, the shell returns the error:

mv: cannot stat `/home/kabaka/Music/Youtube Playlist/Playlists//TextRecords/lastoutput.txt': No such file or directory

That means that where there should the name of a playlist, there is nothing. Do you have any idea why? Is it because $name in my current script and $name in the script above are not the same? Notice that I have the same thing happening for $hash, which should appear in an url but is just blank

回答1:

It's close to working, just say read name hash instead of read line

while read name hash; do
    sh script.sh "$name" "$hash"
done < playlists.txt


回答2:

  1. You can use the output of the echo command as an input file using the pipe,
  2. the flag '-d' defines a delimiter for the 'cut' command.

Here's the code:

while read line
do
    name=`echo $line|cut -f1 -d' '`
    hash=`echo $line|cut -f2 -d' '`
    sh script.sh $name $hash

done < playlists.txt

To your 2nd question: Before moving a file to a directory make sure it exists. You can create it with 'mkdir -p' as follows:

mkdir -p $HOME/Music/Youtube\ Playlist/Playlists/lastoutput.txt


回答3:

You're almost there, and there several ways to do this, but a typical solution is

while read name hash
do
     sh script.sh $name $hash 
done < playlists.txt

IHTH