2

For example:

I want user to input A=a

and I have the command which I guess is totally wrong.


read -p "Enter something:" frsstring=secstring
echo $frsstring
echo $secstring
````````````````````````````````````````````````````````````




1
  • get rid of the = between the two variable names. If you want the user to enter two values separated by and = symbol, set IFS='=' before the read. e.g. IFS== read -p "Enter something:" frsstring secstring
    – cas
    Sep 29, 2019 at 6:26

2 Answers 2

3

In bash you can use an array variable and change the IFS (internal field separator) special variable to = which normally contains space character, tab and newline to split words.

IFS='=' read -a arr -p "Enter something: "
echo "${arr[0]}"
echo "${arr[1]}"

Or you can use shell parameter expansion to remove the longest suffix and prefix pattern from the string:

read -p "Enter something: " str
echo "${str%%=*}" # remove longest suffix pattern `=*`
echo "${str##*=}" # remove longest prefix pattern `*=`
1
  • Thank you Freddy for solving my problem.
    – Will
    Sep 29, 2019 at 6:25
0

I don't know how could it be done with one command, but you could read the entire line, and then split it in the desired variables:

#!/bin/bash

read -p "Enter something:" line
frsstring=`echo "$line" | cut -f1 -d'='`
secstring=`echo "$line" | cut -f2 -d'='`


echo $frsstring
echo $secstring

I hope it could help

1
  • Thank you very much. It solved my problem perfectly.
    – Will
    Sep 29, 2019 at 6:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .