How do I script a "yes" response for installing programs? - linux

I work with Amazon Linux instances and I have a couple scripts to populate data and install all the programs I work with, but a couple of the programs ask:
Do you want to continue [Y/n]?
and pause the install. I want to auto answer "Y" in all cases, I'm just now sure how to do it.

The 'yes' command will echo 'y' (or whatever you ask it to) indefinitely. Use it as:
yes | command-that-asks-for-input
or, if a capital 'Y' is required:
yes Y | command-that-asks-for-input
If you want to pass 'N' you can still use yes:
yes N | command-that-asks-for-input

echo y | command should work.
Also, some installers have an "auto-yes" flag. It's -y for apt-get on Ubuntu.

You might not have the ability to install Expect on the target server.
This is often the case when one writes, say, a Jenkins job.
If so, I would consider something like the answer to the following on askubuntu.com:
https://askubuntu.com/questions/338857/automatically-enter-input-in-command-line
printf 'y\nyes\nno\nmaybe\n' | ./script_that_needs_user_input
Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:
printf 'yyy' | ./script_that_needs_user_input
For sake of completeness you can also use a here document:
./script_that_needs_user_input << EOF
y
y
y
EOF
Or if your shell supports it a here string:
./script <<< "y
y
y
"
Or you can create a file with one input per line:
./script < inputfile
Again, all credit for this answer goes to the author of the answer on askubuntu.com, lesmana.

You just need to put -y with the install command.
For example: yum install <package_to_install> -y

Although this may be more complicated/heavier-weight than you want, one very flexible way to do it is using something like Expect (or one of the derivatives in another programming language).
Expect is a language designed specifically to control text-based applications, which is exactly what you are looking to do. If you end up needing to do something more complicated (like with logic to actually decide what to do/answer next), Expect is the way to go.

If you want to just accept defaults you can use:
\n | ./shell_being_run

Related

Is there a simple alternative to "who am i" and "logname"?

I noticed that RHEL 8 and Fedora 30 don't update the utmp file properly.
As a result, commands such as 'who am i', 'last', 'w' etc print incorrect results (who am i actually doesn't print anything)
After a bit of googling, I found 'logname' which worked in this case but I read that gnome is dropping support for utmp altogether so it's a matter of time until this stops working too.
I wrote the following script which finds the login name of the user (even if he is using sudo the moment he runs the command) but it's way too complicated so I'm looking for alternatives.
LOGIN_UID=$(cat /proc/self/loginuid)
LOGIN_NAME=$(awk -v val=LOGIN_UID -F ":" '$3==val{print $1}' /etc/passwd)
Is there a simple alternative which is not based on proper updating of /var/run/utmp ?
Edit 1: Solutions that don't work $HOME, $USER and id return incorrect values when used in a script that has been run with the sudo command. who am i and logname depend on utmp which isn't always updated by the terminal.
Working solution: After a bit of searching, a simpler way than the aforementioned was found in https://unix.stackexchange.com/users/5685/frederik-deweerdt 's comment to his own answer
Link to answer which contains the commment: https://unix.stackexchange.com/a/74312
Answer 1
stat -c "%U" $(tty)
Second answer found at https://stackoverflow.com/a/51765389/10630167
Answer 2
`pstree -lu -s $$ | grep --max-count=1 -o '([^)]*)' | head -n 1 | sed 's/[()]//g'`
Your question is not well-defined because if X and Y are not working, what are the chances that Z will work? This depends entirely on the precise failure mode you are attempting to handle, and there is nothing in your question to reveal the specific circumstances in which you need this.
With that out of the way, perhaps look at the POSIX id command, which has explicit options to print the real (login) or effective (after any setuid command) user id with -r or -u, respectively. Of course, the precise means by which it obtains this information are not specified, and will remain implementation-dependent, and thus might or might not work on your platform under your specific circumstances.
As an aside, here is a refactoring of your code to avoid polluting the variable name space with two separate variables.
LOGIN_NAME=$(awk 'NR==FNR { val=$0; next }
$3==val{print $1}' /proc/self/loginuid FS=":" /etc/passwd)

Making the script issue "enter" after executing command in shell script [duplicate]

I've created a really simple bash script that runs a few commands.
one of these commands needs user input during runtime. i.e it asks the user "do you want to blah blah blah?", I want to simply send an enter keypress to this so that the script will be completely automated.
I won't have to wait for the input or anything during runtime, its enough to just send the keypress and the input buffer will handle the rest.
echo -ne '\n' | <yourfinecommandhere>
or taking advantage of the implicit newline that echo generates (thanks Marcin)
echo | <yourfinecommandhere>
You can just use yes.
# yes "" | someCommand
You might find the yes command useful.
See man yes
Here is sample usage using expect:
#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }
Check: man expect for further information.
You could make use of expect (man expect comes with examples).
I know this is old but hopefully, someone will find this helpful.
If you have multiple user inputs that need to be handled you can use process substitution and use echo as a 'file' for cat with whatever is needed to handle the first input like this:
# cat ignores stdin if it has a file to look at
cat <(echo "selection here") | command
and then you can handle subsequent inputs by piping the yes command with the answer:
cat <(echo "selection here") | yes 'y' | command

Using -s command in bash script

I have a trivial error that I cant seem to get around. Im trying to return the various section numbers of lets say "man" since it resides in all the sections. I am using the -s command but am having problems. Every time I use it I keep getting "what manual page do you want". Any help?
In the case of getting the section number of a command, you want something like man -k "page_name" | awk -F'-' "/^page_name \(/ {print $1}", replacing any occurrence of page_name with whatever command you're needing.
This won't work for all systems necessarily as the format for the "man" output is "implementation-defined". In other words, the format on FreeBSD, OS X, various flavours of Linux, etc. may not be the same. For example, mine is:
page_name (1) - description
If you want the section number only, I'm sure there is something you can do such as saving the result of that line in a shell variable and use parameter expansion to remove the parentheses around the section number:
man -k "page_name" | awk -F'-' "/^page_name \(/ {print $1}" | while IFS= read sect ; do
sect="${sect##*[(]}"
sect="${sect%[)]*}"
printf '%s\n' "$sect"
done
To get the number of sections a command appears in, add | wc -l at the end on the same line as the done keyword. For the mount command, I have 3:
2
2freebsd
8
You've misinterpreted the nature of -s. From man man:
-S list, -s list, --sections=list
List is a colon- or comma-separated list of `order specific' manual sections to search. This option overrides the
$MANSECT environment variable. (The -s
spelling is for compatibility with System V.)
So when man sees man -s man it thinks you want to look for a page in section "man" (which most likely doesn't exist, since it is not a normal section), but you didn't say what page, so it asks:
What manual page do you want?
BTW, wrt "man is just the test case cuz i believe its in all the sections" -- nope, it is probably only in one, and AFAIK there isn't any word with a page in all sections. More than 2 or 3 would be very unusual.
The various standard sections are described in man man too.
The correct syntax requires an argument. Typically you're looking for either
man -s 1 man
to read the documentation for the man(1) command, or
man -s 7 man
to read about the man(7) macro package.
If you want a list of standard sections, the former contains that. You may have additional sections installed locally, though. A directory listing of /usr/local/share/man might reveal additional sections, for example.
(Incidentally, -s is not a "command" in this context, it's an option.)

How to nest a variable inside a variable?

I have a scenario in which I need to execute the below statement.
air sandbox run $AI_PLAN/Sam_22.plan
For the above command AI should be fetched from a command.
> echo $PREFIX
AI
I tried the below ways
air sandbox run $`echo $PREFIX`_PLAN/Sam_22.plan
returned error : File not found
dollar_prefix=$`echo $PREFIX`
air sandbox run ${dollar_prefix}_PLAN/Sam_22.plan
returned error : File not found
Please let me know where am I going wrong in the above coding.
You're going to need to eval something:
PREFIX=AI
AI_PLAN=some_directory
eval directory=\$${PREFIX}_PLAN
air sandbox run $directory/Sam_22.plan
try using command substitution:
$(command ...)_PLAN
Lets suppose the program make_prefix is in your path. Then:
> make_prefix
AI
> echo $(make_prefix)
AI
> echo $(make_prefix)_PLAN
AI_PLAN
It unclear what you actually want to have happen, but I can guess that you probably want something like
air sandbox ${${PREFIX}_PLAN}/Sam_22.plan
This will take the value of the variable PREFIX (AI in your case?) and append a _PLAN, and use THAT as the name of a variable to fetch

How to check Linux version with Autoconf?

My program requires at least Linux 2.6.26 (I use timerfd and some other Linux-specific features).
I have an general idea how to write this macro but I don't have enough knowledge about writing test macros for Autoconf. Algorithm:
Run "uname --release" and store output
Parse output and subtract Linux version number (MAJOR.MINOR.MICRO)
Compare version
I don't know how to run command, store output and parse it.
Maybe such macro already exists and it's available (I haven't found any)?
I think you'd be better off detecting the specific functions you need using AC_CHECK_FUNC, rather than a specific kernel version.
This will also prevent breakage if you find yourself cross-compiling at some point in the future
There is a macro for steps 2 (parse) and 3 (compare) version, ax_compare_version. For example:
linux_version=$(uname --release)
AX_COMPARE_VERSION($linux_version, [eq3], [2.6.26],
[AC_MSG_NOTICE([Ok])],
[AC_MSG_ERROR([Bad Linux version])])
Here I used eq3 so that if $linux_version contained additional strings, such as -amd64, the comparison still succeeds. There is a plethora of comparison operators available.
I would suggest you not to check the Linux version number, but for the specific type you need or function. Who knows, maybe someone decides to backport timerfd_settime() to 2.4.x? So I think AC_CANONICAL_TARGET and AC_CHECK_LIB or similar are your friends. If you need to check the function arguments or test behaviour, you'd better write a simple program and use AC_LANG_CONFTEST([AC_LANG_PROGRAM(...)])/AC_TRY_RUN to do the job.
Without going too deep and write autoconf macros properly (which would be preferable anyway) don't forget that configure.ac is basically a shell script preprocessed by m4. So you can write shell commands directly.
# prev. part of configure.ac
if test `uname -r |cut -d. -f1` -lt 2 then; echo "major v. error"; exit 1; fi
if test `uname -r |cut -d. -f2` -lt 6 then; echo "minor v. error"; exit 1; fi
if test `uname -r |cut -d. -f3` -lt 26 then; echo "micro error"; exit 1; fi
# ...
This is just an idea if you want to do it avoiding writing macros for autoconf. This choice is not good, but should work...
The best way is the already suggested one: you should check for features; so, say in a future kernel timerfd is no more available... or changed someway your code is broken... you won't catch it since you test for version.
edit
As user foof says in comments (with other words), it is a naive way to check for major.minor.micro. E.g. 3.5.1 will fail because of 5 being lt 6, but 3.5.1 comes after 2.6.26 so (likely) it should be accepted. There are many tricks that can be used in order to transform x.y.z into a representation that puts each version in its "natural" order. E.g. if we expect x, y, or z won't be greather than 999, we can do something like multiplying by 1000000 major, 1000 minor and 1 micro: thus, you can compare the result with 2006026 as Foof suggested in comment(s).

Resources