Search This Blog

Sunday, January 1, 2012

One line Bash script debugging

Working on the Bash shell can be very effective. You can combine various command line programs and chain (pipe) them together to accomplish a bigger task. Sometimes you have to debug your one line scripts although.

When working on the CLI I wrote in a hurry a small command to find and check the value of the sched_autogroup_enabled Linux  kernel variable [1] under the proc file system.

To my first surprise it didn't work at all.

root@udesktop:/proc# find . -name \*sched\* 2>/dev/null  | grep -v [0-9]
root@udesktop:/proc# 

It is easy to find this file manualy and I did it. Below is the prove that the file exist that I was looking for.

root@udesktop:/proc# ls -la ./sys/kernel/sched_autogroup_enabled
-rw-r--r-- 1 root root 0 2012-01-01 21:38 ./sys/kernel/sched_autogroup_enabled

Problem
How to debug one line bash scripts. Or in general how to debug any bash script.

Solution
The problem is easy to see once we enable more verbose debug output from the Bash

root@udesktop:/proc# set -v -x
root@udesktop:/proc# find . -name \*sched\* 2>/dev/null  | grep -v [0-9]
find . -name \*sched\* 2>/dev/null  | grep -v [0-9]
+ find . -name '*sched*'
+ grep --color=auto -v 1 2 3 5 6 7 8 9

We see that the string '[0-9]' is extended by the bash before the command chain is actually executed.

Once we know that the problem is how our regular expression [2] is evaluated the fix is simple:

root@udesktop:/proc# find . -name \*sched\* 2>/dev/null  | grep -v '[0-9]'
find . -name \*sched\* 2>/dev/null  | grep -v '[0-9]'
+ find . -name '*sched*'
+ grep --color=auto -v '[0-9]'
./schedstat
./sched_debug
./sys/kernel/sched_child_runs_first
./sys/kernel/sched_min_granularity_ns
./sys/kernel/sched_latency_ns
./sys/kernel/sched_wakeup_granularity_ns
./sys/kernel/sched_tunable_scaling
./sys/kernel/sched_migration_cost
./sys/kernel/sched_nr_migrate
./sys/kernel/sched_time_avg
./sys/kernel/sched_shares_window
./sys/kernel/sched_rt_period_us
./sys/kernel/sched_rt_runtime_us
./sys/kernel/sched_compat_yield
./sys/kernel/sched_autogroup_enabled
./sys/kernel/sched_domain

References
[1]
Benefiting of sched_autogroup_enabled on the desktop
http://unix.stackexchange.com/questions/9069/benefiting-of-sched-autogroup-enabled-on-the-desktop

The ~200 Line Linux Kernel Patch That Does Wonders
http://www.phoronix.com/scan.php?page=article&item=linux_2637_video&num=1

[2]
Bash Reference Manual
http://www.gnu.org/software/bash/manual/bashref.html#Filename-Expansion

Debugging Bash scripts
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html

No comments:

Post a Comment