Why does my Bash variable come back empty when the command works in the terminal?

0
8
Asked By MellowCedar42 On

I'm trying to update an old Steam Deck screen-rotation script. The original version used xrandr, but after switching from X11 to Wayland, I rewrote it to use kscreen-doctor instead:

#!/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

The pipeline returns 8 when I run it directly in a terminal, but screen_info appears to be empty when the same command runs inside the script. I'm not sure whether the problem is the command, the field being extracted, or the conditional. Is there a good way to debug a Bash script step by step, similar to stepping through an Excel formula?

2 Answers

Answered By QuietMarble7 On

Break the pipeline into separate commands and print each intermediate result. For example, store the output of kscreen-doctor in one variable, print it, then run grep on that variable and print the result, and finally inspect what awk extracts. That will show exactly where the value disappears. You can also run the script with `bash -x scriptname.sh` to have Bash print each command as it executes. Since the Deck only has one display, you may not need grep at all, but first verify the exact output and field positions.

MellowCedar42 -

That makes sense. The problem is that the pipeline gives me 8 in the terminal but an empty value in the script. I’ll separate the commands and echo each result to find the failing step. Since there’s only one screen, I’ll also test removing grep.

Answered By SilverPine_31 On

Double-check the option passed to kscreen-doctor. The command in the script uses `--o`, while the short output option may need to be `-o` instead. Also run the command without awk and inspect the raw output, because the value may not always be the third whitespace-separated field. Once the raw text and field number are confirmed, the assignment should be easier to fix.

MellowCedar42 -

I wasn’t sure about the difference between a single and double dash, so I’ll verify the correct option. I’ll also inspect the unprocessed kscreen-doctor output to confirm that awk is reading the expected field.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.