Saturday, April 20, 2024
28
rated 0 times [  28] [ 0]  / answers: 1 / hits: 30462  / 3 Years ago, thu, november 4, 2021, 6:01:07

I have the following script. It's a simple test case where a is any string value and b is supposed to be a path.



#!/bin/bash

alias jo "
echo "please enter values "
read a
read -e b
echo "My values are $a and $b""


However whenever I try to execute ./sample.sh I get the following errors:



./sample.sh: line 3: alias: jo: not found
./sample.sh: line 3: alias: echo please: not found
./sample.sh: line 3: alias: enter: not found
./sample.sh: line 3: alias: values: not found
./sample.sh: line 3: alias: read a read -e b echo My: not found
./sample.sh: line 3: alias: values: not found
./sample.sh: line 3: alias: are: not found
./sample.sh: line 3: alias: and: not found
./sample.sh: line 3: alias: : not found


and when I try source sample.sh I get the following:



a: Undefined variable.


My aim was to make this an alias so that I can source this script and just run the alias to execute the line of commands. Can someone look at this and let me know what the error is?


More From » command-line

 Answers
0

You have a couple of issues here




  1. unlike in csh, in bash (and other Bourne-like shells), aliases are assigned with an = sign e.g. alias foo=bar


  2. quotes can't be nested like that; in this case, you can use single quotes around the alias and double quotes inside


  3. the backslash is a line continuation character: syntactically, it makes your command into a single line (the opposite of what you want)




So



#!/bin/bash

alias jo='
echo "please enter values "
read a
read -e b
echo "My values are $a and $b"'


Testing: first we source the file:



$ . ./myscript.sh


then



$ jo
please enter values
foo bar
baz
My values are foo bar and baz


If you want to use the alias within a script, then remember that aliases are only enabled by default in interactive shells: to enable them inside a script you will need to add



shopt -s expand_aliases


Regardless of everything above, you should consider using a shell function rather than an alias for things like this


[#7291] Friday, November 5, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dileble

Total Points: 169
Total Questions: 105
Total Answers: 141

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;