Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split input using bash?

Tags:

linux

bash

I have to write a script in Linux, that takes input from user.

For example, this could be a line of input:

name = Ruba

I need to take the "Ruba" from the input, so how can i split the input and take the last part?

like image 560
Ruba Avatar asked Feb 23 '23 00:02

Ruba


1 Answers

You can use IFS in bash, which is the "internal field separator" and tells bash how to delimit words. You can read your input in with IFS set to a space (or whatever delimiter) and get an array back as input.

#!/usr/bin/env bash

echo "Type in something: "

# read in input, using spaces as your delimiter.
# line will be an array
IFS=' ' read -ra line

# If your bash supports it, you can use negative indexing
# to get the last item
echo "last item is: ${line[-1]}"

Test run:

$ ./inscript.sh 
Type in something: 
name = ruba
last item is: ruba
like image 80
逆さま Avatar answered Feb 28 '23 00:02

逆さま