Reading Values In Bash
When you work on the command line, the majority of the time, creating command pipelines and redirecting output to files. But there are times when you put data into variables. Sure, you can capture the output from a command using backticks. But you can also use the read
command. This is normally used to prompt the user for a value.
# Prompt the user for an answer
read -p 'Pick a number between 1 and 100' guess
This is particularly useful in a script. This allows you to change behavior depending upon the value the user provides. But you might not want a prompt. One feature of the read commands is that you can store multiple values in separate variables in a single call.
In my job hunt, I’ve been using LibreOffice to track the jobs I’m applying to. There are three fields in my spreadsheet I need data from – the company, the position I’m applying for, and the URL of the job posting. Lets build up a command to acheieve our desired result.
read company position url <<< "'Company Name' 'Job Title' 'https://example.com'"
You can test the output with this echo command
echo "Company=${company}
Position=${position}
URL=${url}
"
You’ll notice that while you’re seeing the data, it’s not lining up the way that it should. This is because Bash reads content as whitespace delimited. is seeing the space in company name even though we quoted it. So lets tell Bash to use a different value to delimit our data. Well change the value of the IFS variable to use the @ symbol. Since we’re working with URLs (and not email addresses), we should be fine. By preceding the read command with the assignment of IFS, we modify the value for just this command. We need to also modify our test data string to delimit the data with the @ symbol.
IFS='@' read company position url <<< "Company Name@Job Title@https://example.com"
The mechanics of the read command look good. Now lets make it so we can copy/paste our data from LibreOffice. In LibreOffice, select the columns for a single row. Your company, position, and url columns must be contiguous and in order – so the values correspond to the variables.
Now we need to replace our test data, with a command to read from the system clipboard. It’s pbpaste
to the rescue! If we just paste the content as-is, it’ll be tab-delimited. So we need to pipe it to sed
to replace every tab character with an @ symbol, since that is our new delimiter.
IFS='@' read company position url <<< "$(pbpaste | sed 's/\t/@/g')"
This is a lot to remember. So, you’ll want to make a bash function in your dotfiles. This is more useful when it’s part of a larger work – even if its just a function. So I hope that helps. Happy computing.