I have this bash script that I use with i3wm to toggle between screen modes (external screen, internal screen, all or mirror). The first part of the script grabs the name of the screens. If I copy the following part and runit in a terminal:
#!/bin/bash
xrandr|grep " connected primary"|IFS=" " read INTERNAL_OUTPUT con
xrandr|awk '/ connected/ && !/ primary/'|IFS=" " read EXTERNAL_OUTPUT con
echo internal monitor is $INTERNAL_OUTPUT
echo external monitor is $EXTERNAL_OUTPUT
...
I get something like
$ ./script.sh
internal monitor is eDPI
external monitor is DPI-1
But when I run the actual script, the variables are empty and all I see is
$ ./script.sh
internal monitor is
external monitor is
What is the diference when setting the variables inside a script?
echocommands are in the same script as thereadcommands they should work, but they won't work outside the script unless you call it with the./sourcecommand.xrandr|grep " connected primary"|{ IFS=" " read INTERNAL_OUTPUT con; echo internal monitor is $INTERNAL_OUTPUT; }, and similarly for the other monitor. This works in both the terminal and a script.bash, and your console isn'tbash(so they work there)(what saysls -l /proc/$$/exe?) but your script requires bash (due to shebang) so uses bash rules and this makes the code fail.bash, you need something likeINTERNAL_OUTPUT=$(xrandr|grep " connected "|grep -o '^[^ ]*'). This makesINTERNAL_OUTPUTavailable on subsequent lines in the script, though not on returning to the terminal unless called with.. If you want a script to set variables in the current shell without calling.you need to code it as a function.