Вот (непроверенный) пример с использованием Javascript и PHP и методологии, объясненной Энтоном. Не зацикливайтесь на синтаксисе и на том, работает это или нет, вы сможете исправить это позже. Обратите внимание на патер с сильным акцентом на валидацию данных.
Javascript:
if (validate()) { // Preliminary data check to preven unecessary request
$.ajax(
'/path/to/your-script', { // the URL where the php script is hosted
'action': 'update', // variables passed to the server
'id': '123',
'value': 'New Value'
}, function (response) { // server response
if (typeof(response.success) == 'number' && response.success) {
}
}, 'json' // data format
);
}
Рудиментарный шаблон PHP:
// Make sure that the POST is done via ajax
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// Template for multiple commands.
switch ($_POST['action']) { // Catch all commands
case 'update':
// Make sure to clean up the value. Lookup tutorials on Google
$id = sanitize($_POST['id'];
$value = sanitize($_POST['value'];
// Although sanitized make sure that the values pass certain
// criteria such as duplicates, data type, user privileges etc
if (validate($id, $value) {
shell_exec("your '" . $id . "' '" . $value . "'";
}
break;
// If we do not know what this is we can throw an exception
default:
throw new Exception ('Unknown Request');
}
// This is just an acknowledgement that the command executed.
// More validation and try catch constructs are highly recommended.
echo json_encode([
'success' => 1
]);
}
Это соответствует вашим требованиям?
#!/bin/sh
if test -n "$1"; then
echo "Read from $1";
elif test ! -t 0; then
echo "Read from stdin"
else
echo "No data provided..."
fi
Основные приемы заключаются в следующем:
Обнаружение того, что у вас есть аргумент, выполняется с помощью test -n $1
, который проверяет, существует ли первый аргумент.
Затем проверка того, не открыт ли stdin
на терминале (, потому что он передан в файл ), выполняется с помощьюtest ! -t 0
(проверка того, не является ли нулевой файловый дескриптор (, также известный как stdin
). открыть ).
И, наконец, все остальное подпадает под последний случай(No data provided...
).
Я искал повсюду, но безрезультатно, и, наконец, мне удалось собрать это воедино путем множества проб и ошибок. С тех пор он безупречно работал у меня во многих -случаях использования.
#!/bin/bash
### LayinPipe.sh
## Recreate "${@}" as "${Args[@]}"; appending piped input.
## Offers usable positional parameters regardless of where the input came from.
##
## You could choose to create the array with "${@}" instead following
## any piped arguments by simply swapping the order
## of the following two 'if' statements.
# First, check for normal positional parameters.
if [[ ${@} ]]; then
while read line; do
Args[${#Args[@]}]="${line}"
done < <(printf '%s\n' "${@}")
fi
# Then, check for piped input.
if [[ ! -t 0 ]]; then
while read line; do
Args[${#Args[@]}]="${line}"
done < <(cat -)
fi
# Behold the glory.
for ((a=0;a<${#Args[@]};a++)); do
echo "${a}: ${Args[a]}"
done
$ ls
: TestFile.txt 'Filename with spaces'
$ ls -1 | LayinPipe.sh "$(ls -1)"
> 0: Filename with spaces
> 1: TestFile.txt
> 2: Filename with spaces
> 3: TestFile.txt
$ LayinPipe.sh "$(ls -1)"
> 0: Filename with spaces
> 1: TestFile.txt
$ ls -1 | LayinPipe.sh
> 0: Filename with spaces
> 1: TestFile.txt
[РЕШЕНО] в оболочке bash...
... читать -t 0 :см. «помощь по чтению»
$ function read_if_stdin_not_empty {
if read -t 0 ; then
while read ; do
echo "stdin receive : $REPLY"
read_if_stdin_not_empty
done
else
echo "stdin is empty.."
fi
}
# TESTs:
$ read_if_stdin_not_empty
stdin is empty..
$ echo '123' | read_if_stdin_not_empty
stdin receive : 123
$s='123
456'
$ echo "$s" | read_if_stdin_not_empty
stdin receive : 123
stdin receive : 456