Why does my Bash command work in the terminal but return an empty value in a script?

September 6, 2026 2 answers
Asked by MellowPine47
I'm trying to adapt a Steam Deck screen-rotation script for Wayland. The original script used xrandr, so I rewrote it to use kscreen-doctor: #!/bin/bash screen="eDP-1" default_screen_orientation=8 screen_info=$(kscreen-doctor -o | grep "$screen" | awk '/Rotation/ {print $3}') if [[ "$screen_info" -eq "$default_screen_orientation" ]]; then kscreen-doctor output.eDP-1.rotation.right else kscreen-doctor output.eDP-1.rotation.none fi When I run the kscreen-doctor, grep, and awk pipeline directly in a terminal, it returns 8 as expected. However, when the same command runs inside the script, screen_info is empty or null. I'm new to Bash and would appreciate help finding the problem. Is there also a way to step through a Bash script similarly to stepping through an Excel formula?

Answers

SilverMaple_19
Verify the output format before assuming that field 3 is the rotation value. Run `kscreen-doctor -o` by itself, then try the command without `awk` and inspect the exact line that contains `Rotation`. Formatting or a slightly different output in the script can make the pattern fail. You can also make the script stop on errors and show commands as they execute by adding `set -euxo pipefail` near the beginning. If the command works interactively but not from the script, compare the shell, PATH, and environment used to launch the script.

QuietHarbor8: I wasnโ€™t sure whether `--o` and `-o` were equivalent, so Iโ€™ll check that first. Iโ€™ll also inspect the raw output and confirm which field contains the value instead of relying on the terminal result alone.

Reply to this answer
CedarFox_62
Start by checking each stage of the pipeline separately instead of assigning everything at once. For example: output=$(kscreen-doctor -o) printf '%sn' "$output" filtered=$(printf '%sn' "$output" | grep "$screen") printf '%sn' "$filtered" rotation=$(printf '%sn' "$filtered" | awk '/Rotation/ {print $3}') printf 'rotation=[%s]n' "$rotation" That will show exactly where the expected text disappears. Also quote variables when passing their contents to other commands. Bash tracing can help too: run the script with `bash -x script.sh`, or add `set -x` near the top. One detail worth checking is the option spelling: use `-o` if that is what kscreen-doctor expects, rather than `--o`.

MellowPine47: That makes sense. The problem is with the value assigned to screen_info, not the if statement. Iโ€™ll split up the pipeline and print each intermediate result. Since the Deck only has one display, I may be able to simplify the command as well.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions