Question

I've been scratching my head over this one for a while now. It seems so simple yet I just can't get it to work. This is on a rooted android tablet, if that makes a difference. I'm trying to imitate the behavior of sudo on a normal linux system. I'm not very experienced when it comes to bash scripting, so this is probably very simple. This is a two part problem.

So here's (part of) a bash script called aliases. It is sourced by bashrc normally. The problem is that I want my custom sudo command to have access to the aliases defined in this script.

#! /system/xbin/bash

alias ls='busybox ls --color=auto'

function sudo() {
    su -c 'source /system/etc/bash/aliases && "$@"'
} 

So when I call sudo from a shell it outputs absolutely nothing. A quick 'echo ok' at the end of the above script proves that the source command is being executed when I attempt to sudo something. But nothing seems to be done after '&&'. Not even echo. Not even touching a random filename works, so it doesn't seem to be stdout being redirected or something. I've tried substituting '&&' with '||' but that doesn't work either.

Part two of the problem emerged when debugging. Calling the following from a shell:

su -c 'source /system/etc/bash/aliases && ls'

... outputs ls without colors, even though the aliases file was sourced immediately before ls was called. Now I'm thoroughly confused.

Était-ce utile?

La solution

Your immediate problem is that you have surrounded your command in single quotes:

su -c 'source /system/etc/bash/aliases && "$@"'

The single quotes mean that the "$@" is not expanded inside the function, so you're running the literal command...

source /system/etc/bash/aliases && "$@"

...and the "$@" expands to an empty string. If you can live without needed to handle quoted arguments, you could do this:

    su -c "source /system/etc/bash/aliases && $*"

Note the use of double quotes ("...") instead of single quotes. However, this may still not do what you need, because of this:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).

In general, I try to avoid the use of aliases in shell scripts, because it makes the script heavily dependent on your environment (or in this case, the environment of the target user). Using shell scripts instead of aliases to encapsulate commands will generally result in a more robust and portable solution.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top