Exercícios e Exemplos do Livro
Exercícios e exemplos do livro
Programação Shell do Linux – 10ª Edição
Autor: Julio Cezar Neves
==== add ====
$ cat add
#
# Adiciona Pessoas ao Arquivo de Telefones - Versao 2
#
echo "$1 $2" >> telefones
sort -o telefones telefones
==== alfa ====
$ cat alfa
acd
cdr
swax
==== aluado ====
$ cat aluado
Lua Nova
Linguagem Lua
Lua Cheia
Luanda é a capital de Angola
Essa linha é louca
==== anilhas.sh ====
$ cat anilhas.sh
#!/bin/bash
# O prg serve para contar a quantidade de cada anilha teria de usar
#+ para fazer uma cabeação.
#+ Anilhas são aqueles pequenos anéis numerados que você vê nos cabos
#+ de rede, que servem para identificá-los.
[[ $# != 2 ]] && {
echo "Uso: $0 '
exit 1
}
Tudo=$(eval echo {$1..$2}) # Recebe os num. entre $1 e $2
Tudo=${Tudo// /} # Tira os brancos gerados pelo cmd anterior
echo $Tudo::::${#Tudo}; read
for ((i=0; i<${#Tudo}; i++))
{
let Algarismo[${Tudo:i:1}]++ # Incrementa vetor do algarismo
}
for ((i=0; i<=9; i++))
{
printf "Algarismo %d = %2d\n" \
$i ${Algarismo[$i]:-0} # Se o elemento for vazio, lista zero
}
==== animal.sh ====
$ cat animal.sh
#!/bin/bash
# Separa animais selvagens e domésticos
declare -A Animais
Animais[cavalo]=doméstico
Animais[zebra]=selvagem
Animais[gato]=doméstico
Animais[tigre]=selvagem
Animais[urso pardo]=selvagem
for Animal in "${!Animais[@]}"
do
if [[ "${Animais[$Animal]}" == selvagem ]]
then
Sel=("${Sel[@]}" "$Animal")
else
Dom=("${Dom[@]}" "$Animal")
fi
done
Maior=$[${#Dom[@]} > ${#Sel[@]}?${#Dom[@]}:${#Sel[@]}]
clear
tput bold; printf "%-15s%-15s\n" Domésticos Selvagens; tput sgr0
for ((i=0; i<$Maior; i++))
{
tput cup $[1+i] 0; echo ${Dom[i]}
tput cup $[1+i] 14; echo ${Sel[i]}
}
==== aniv ====
$ cat aniv
1919-11-08 Hedy Coutinho
1947-07-05 Silvina Duarte
1980-01-17 Juliana Duarte
1984-11-08 Paula Duarte
==== AnoNovo.sh ====
$ cat AnoNovo.sh
#!/bin/bash
#
# Brincadeira de Ano Novo
# Autor: Julio Neves
#
trap 'tput cnorm; tput sgr0; clear; exit' 0 2 3 15
Feliz[1]="FFFFFFF EEEEEEE LLL III ZZZZZZZ 22222 0000 1111 33333 "
Feliz[2]="FFFFFFF EEEEEEE LLL III ZZZZZZZ 2222222 000000 11111 333 333 "
Feliz[3]="FFF EEE LLL III ZZZ 22 222 000 000 11 111 33 333"
Feliz[4]="FFFFF EEEEE LLL III ZZZ 222 000 000 111 333 "
Feliz[5]="FFFFF EEEEE LLL III ZZZ 222 000 000 111 333 "
Feliz[6]="FFF EEE LLL III ZZZ 222 000 000 111 33 333"
Feliz[7]="FFF EEEEEEE LLLLLLL III ZZZZZZZ 2222222 000000 1111111 333 333 "
Feliz[8]="FFF EEEEEEE LLLLLLL III ZZZZZZZ 2222222 0000 1111111 33333 "
LargTela=$(tput cols)
while ((${#Feliz[1]}>=LargTela))
do
zenity --error --title "Feliz Natal" --text "Esta arte ascii ;) precisa de uma tela com uma largura mínima de ${#Feliz[1]} caracteres" || exit 1
LargTela=$(tput cols)
done
ColCab=$((($(tput cols)-${#Feliz[1]})/2))
Cor=6
function ApagaAcende
{
tput cup $[Lin - 4] $[Meio + 1]
((n == 0)) && {
echo "TIM TIM"
n=1
return
}
tput el
n=0
}
function Cab
{
Cor=$[Cor == 7?0:++Cor]
tput setaf $Cor; tput bold
for ((kk=1; kk<9; kk++))
{
tput cup $((kk-1)) $ColCab
echo "${Feliz[kk]}"
}
tput setaf 3
}
function FazBolha
{
for k in 1 2
do
y=0
for Sai in 2 4 6 6
do
C1=$[Sai == 2?$[Meio + 1]:$[Sai == 4?Meio - 0:Meio - 1]]
C2=$[Sai == 2?$[Meio + 7]:$[Sai == 4?Meio + 6:Meio + 5]]
Var=
for ((j=1; j<=Sai; j++))
{
Var=$Var$[RANDOM % 2]" "
}
x=0
let y++
for SN in $Var
do
((SN)) && {
tput cup $[Lin + 2 - y] $[k == 1?C1 + x:C2 + x]
echo .
}
let x++
done
done
done
}
Cols=5
Fim=$(tput cols)
while ((Fim < 96))
do
tput flash
zenity --error --text "Ponha o terminal em\nModo de tela cheia" || exit 1
Fim=$(tput cols)
done
Meio=$[Fim / 2 - 5]
Lin=$[$(tput lines) - 7]
tput civis
tput setab 1
tput bold
tput setaf 3
clear
for ((i=1; i<$Meio; i++))
do
tput cup $Lin $[i - 1]; echo ' '
tput cup $[Lin + 1] $[i - 1]; echo ' '
tput cup $[Lin + 2] $[i - 1]; echo ' '
tput cup $[Lin + 3] $[i - 1]; echo ' '
tput cup $[Lin + 4] $[i - 1]; echo ' '
tput cup $[Lin + 5] $[i - 1]; echo ' '
tput cup $Lin $i; echo '\____/'
tput cup $[Lin + 1] $i; echo ' \ /'
tput cup $[Lin + 2] $i; echo ' \/'
tput cup $[Lin + 3] $i; echo ' ||'
tput cup $[Lin + 4] $i; echo ' ||'
tput cup $[Lin + 5] $i; echo ' (__)'
tput cup $Lin $[Fim - i - 5]; echo ' '
tput cup $[Lin + 1] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 2] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 3] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 4] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 5] $[Fim - i - 5]; echo ' '
tput cup $Lin $[Fim - i - 6]; echo '\____/'
tput cup $[Lin + 1] $[Fim - i - 6]; echo ' \ /'
tput cup $[Lin + 2] $[Fim - i - 6]; echo ' \/'
tput cup $[Lin + 3] $[Fim - i - 6]; echo ' ||'
tput cup $[Lin + 4] $[Fim - i - 6]; echo ' ||'
tput cup $[Lin + 5] $[Fim - i - 6]; echo ' (__)'
Cab
done
for ((f=0; f<5; f++))
{
tput flash
sleep 0.02
}
while true
do
((++Conta % 6)) || ApagaAcende
FazBolha
Cab
sleep 0.05
y=0
for Sai in 2 4 6 6
do
let y++
C1=$[Sai == 2?$[Meio + 1]:$[Sai == 4?Meio - 0:Meio - 1]]
C2=$[Sai == 2?$[Meio + 7]:$[Sai == 4?Meio + 6:Meio + 5]]
for ((j=1; j<=Sai; j++))
{
Trab="$Trab"$(((Sai == 4)) && echo -n _ || echo -n ' ')
}
tput cup $[Lin + 2 - y] $C1
echo "$Trab"
tput cup $[Lin + 2 - y] $C2
echo "$Trab"
Trab=
done
Cab
sleep 0.05
done
==== Arq ====
$ cat Arq
Lua Nova
Linguagem Lua
Lua Cheia
Luanda é a capital de Angola
Essa linha é louca
==== arq.DOS ====
$ cat arq.DOS
Este arquivo foi
gerado por um ftp
mal feito do DOS
ou rWin para o Linux.
==== ArqOLs ====
$ cat ArqOLs
01 durjcv01 bolpetti cgrippi jneves lcarlos rhudson ngerhard lfurtado ecardoso rlegaria
02 dualco01 walfredo dlima mlourdes frodrigu magali avoss
03 duamcd01 mbranco jbrito aguedes mdutra mandrade
04 dubapo01 vgomes lmattos cneri slima mandrade wsantos lleite rmacedo
05 ducesd01 francis sfelicio leonardo jacque ervedosa
06 dumsap01 igormang rmurillo aroracio rosgomes mishikaw cbraz
07 duesjm01 d306487 d200034 d243442 d285706
08 dugoae01 oclotild rgaleno santonia sgildazi cnatal jpeixoto
09 dumaec01 chicoc raquiles adiniz cpinto lcaldas mbarros jcoelho
10 dumtgv01 nneves isouza abueno
11 dumgpm01 jortiz jribeiro ocastro cmilu mcosta omaciel lleite mbela ecastro echaves
12 dupadc01 mbraga ssilva jbarbosa hkikuchi jmatos jademir
13 dupbgp01 ttania tdaniel semanuel bmichele
14 duprtl01 d226807 d223336 d271241 d324612 d324566
15 dupedb01 alyra soraya edilson erika gsilva marcos venicio mmelo
16 dupiss01 jroberto jteodoro cgercira abezerra
17 durjbf01 d230910 d222127 d227480 d226149 d213195 d220655 d296996 d299316
18 durnap01 acamara gmary george solon acosta mbarbosa
19 dursbm01 d290343 d209228 d211788 d223638 d324299 d219657 d301639 d324302 d244651 d240109 d305391 d226262 d324329
20 duscfs01 palves ademirf jamirs luizfi
21 duspmv01 esatiro jjunior tlucia pfreire kikegami
22 duseip01 marcia prado denise sergio milson ecorreia alima msilva
23 dudfas01 ovania fjuci gidenis sleo
28 dutons01 afeitosa esilva ijunior hcoelho
==== ArteAscii1.sh ====
$ cat ArteAscii1.sh
#!/bin/bash
# Versão 2.0
# Isso foi feito para mostrar que em shell se
# pode fazer de tudo, inclusive na tela.
#
# Autor: Julio Neves
#
trap "tput reset; tput cnorm; exit" 2
# Troque Julio Neves pelo seu nome para enviar a amigos, mas
#+ sempre pelo menos 2 e somente 2 nomes ;)
#+ O nome tb pode ser passado como parâmetro.
NomeIni=(${*:-Julio Neves})
# Feliz Ano ...
#+ Se já passou do meio do ano, este ano mais 1, senão este ano
Ano=$[$(date +%j)>365/2?$(date +%Y)+1:$(date +%Y)]
function MontaArr
{
# Monta um array Arr[$Lin$Col] (ambas com zeros à esqueda)
#+ com o caracteres que está naquela posição
local i
local l
for ((i=0; i<${#3}; i++))
{
l="${3:i:1}"
Arr[$(printf "$1%02i" $[$2+$i])]="$l:$4"
}
}
# Preparando nome para escrever no canto inferior direito da tela
for ((Pos=0; ;Pos++))
{
s0=${NomeIni[0]:$Pos:1}
s0=${s0:- }
s1=${NomeIni[1]:$Pos:1}
s1=${s1:- }
[[ $s0 == ' ' && $s1 == ' ' ]] && break
Nome="$Nome$s0 $s1"
}
# UltLin="São os votos de "$Nome" para você e sua família"
# UltCol=$[($(tput cols) - ${#UltLin}) / 2]
# Montando a Árvore
ColLogo=$[$(tput cols)-4]
LinLogo=$[$(tput lines)-$Pos-1]
LogoTrab=0
tput civis
lin=2
col=$(($(tput cols) / 2))
ccnev=$[col - 13]
c=$((col-1))
est=$((c-2))
cor=0
tput setab 0; clear
tput setaf 2; tput bold
for ((i=1; i<20; i+=2))
{
tput cup $lin $col
for ((j=1; j<=i; j++))
{
echo -n \*
MontaArr $lin $[col+j] \* 2
}
let lin++
let col--
}
tput sgr0; tput setab 0; tput setaf 3; tput bold
for ((i=1; i<=2; i++))
{
MontaArr $lin $[c+1] mWm 3
tput cup $((lin++)) $c
echo mWm
}
tput setab 0; tput setaf 7; tput bold
tput cup $lin $((c - 4)); echo BOAS FESTAS
MontaArr $lin $[c-3] "BOAS FESTAS" 7
tput cup $((lin + 1)) $((c - 11)); echo E muito suSHELLso em $Ano
MontaArr $((lin + 1)) $((c - 10)) "E muito suSHELLso em $Ano" 7
# tput cup $((lin + 3)) $UltCol; echo $UltLin
let c++
k=1
# Pendurando as bolas (da árvore, claro!)
while true
do
for ((i=1; i<=35; i++))
{
# Apagando a bola que foi ligada há 35 rodadas atras
[ $k -gt 1 ] && {
tput setab 0; tput setaf 2; tput bold
tput cup ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]}; echo \*
MontaArr ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]} \* 2
unset linha[$[k-1]$i]; unset coluna[$[k-1]$i] # Mantenha limpo o vetor
}
li=$((RANDOM % 9 + 3))
ini=$((c-li+2))
fim=$((c+li+2))
co=$((RANDOM % (li-2) * 2 + 1 + ini))
tput setab 0; tput setaf $cor; tput bold # Troca cor das bolas
tput cup $li $co
echo o
linha[$k$i]=$li
coluna[$k$i]=$co
MontaArr $li $co o $cor
sh=1
for l in S H E L L
do
tput cup $((lin+1)) $((c-3+sh))
echo $l
let sh++
done
# Olha a neve
for ((n=0; n<15; n++))
{
[ "${nev[n]}" ] || {
nev[n]=$[$RANDOM % 12 + 1]$(printf "%02i" $[RANDOM % 28 + ccnev])
}
lnev=$[nev[n] / 100]
cnev=$[nev[n] % 100]
idx=$lnev$(printf "%02i" $cnev)
Antigo=${Arr[10#$idx-100]%:*}
Antigo=${Antigo:-' '}
CorAnt=${Arr[10#$idx-100]#*:}
CorAnt=${CorAnt:-0}
tput setab 0
tput setaf $CorAnt
tput cup $[lnev-1] $[cnev-1]
echo "$Antigo"
tput setab 0; tput setaf 7; tput cup $lnev $[cnev-1]; echo .
let lnev++
nev[n]=$lnev$(printf "%02i" $cnev)
[ $lnev -gt 16 ] && {
tput setab 0; tput setaf 7; tput cup $[lnev-1] $[cnev-1]; echo " "
unset nev[n]
}
tput setaf $[n%7+1]
tput cup $[LinLogo+LogoTrab] $ColLogo
echo "${Nome:$[LogoTrab*3]:3}"
(( LogoTrab++ == Pos-1)) && {
LogoTrab=0
}
}
cor=$(((cor+1)%8))
}
k=$((k % 2 + 1))
done
==== ArteAscii2.sh ====
$ cat ArteAscii2.sh
#!/bin/bash
#
# Brincadeira de Ano Novo
# Autor: Julio Neves
#
trap 'tput cnorm; tput sgr0; clear; exit' 0 2 3 15
Feliz[1]="FFFFFFF EEEEEEE LLL III ZZZZZZZ 22222 0000 1111 33333 "
Feliz[2]="FFFFFFF EEEEEEE LLL III ZZZZZZZ 2222222 000000 11111 333 333 "
Feliz[3]="FFF EEE LLL III ZZZ 22 222 000 000 11 111 33 333"
Feliz[4]="FFFFF EEEEE LLL III ZZZ 222 000 000 111 333 "
Feliz[5]="FFFFF EEEEE LLL III ZZZ 222 000 000 111 333 "
Feliz[6]="FFF EEE LLL III ZZZ 222 000 000 111 33 333"
Feliz[7]="FFF EEEEEEE LLLLLLL III ZZZZZZZ 2222222 000000 1111111 333 333 "
Feliz[8]="FFF EEEEEEE LLLLLLL III ZZZZZZZ 2222222 0000 1111111 33333 "
LargTela=$(tput cols)
while ((${#Feliz[1]} >= LargTela))
do
zenity --entry --title "Feliz Ano Novo" --text "Esta arte ascii ;) precisa de uma tela com\numa largura mínima de ${#Feliz[1]} caracteres.\n\n\t\t- Amplie a tela e clique OK\n\t\t- Clique Cancelar para sair" || exit 1
LargTela=$(tput cols)
done
ColCab=$((($(tput cols)-${#Feliz[1]})/2))
Cor=6
function ApagaAcende
{
tput cup $[Lin - 4] $[Meio + 1]
((n == 0)) && {
echo "TIM TIM"
n=1
return
}
tput el
n=0
}
function Cab
{
Cor=$[Cor == 7?0:++Cor]
tput setaf $Cor; tput bold
for ((kk=1; kk<9; kk++))
{
tput cup $((kk-1)) $ColCab
echo "${Feliz[kk]}"
}
tput setaf 3
}
function FazBolha
{
for k in 1 2
do
y=0
for Sai in 2 4 6 6
do
C1=$[Sai == 2?$[Meio + 1]:$[Sai == 4?Meio - 0:Meio - 1]]
C2=$[Sai == 2?$[Meio + 7]:$[Sai == 4?Meio + 6:Meio + 5]]
Var=
for ((j=1; j<=Sai; j++))
{
Var=$Var$[RANDOM % 2]" "
}
x=0
let y++
for SN in $Var
do
((SN)) && {
tput cup $[Lin + 2 - y] $[k == 1?C1 + x:C2 + x]
echo .
}
let x++
done
done
done
}
Cols=5
Fim=$(tput cols)
# while ((Fim < 96))
# do
# tput flash
# zenity --error --text "Ponha o terminal em\nModo de tela cheia" || exit 1
# Fim=$(tput cols)
# done
Meio=$[Fim / 2 - 5]
Lin=$[$(tput lines) - 7]
tput civis
tput setab 1
tput bold
tput setaf 3
clear
for ((i=1; i<$Meio; i++))
do
tput cup $Lin $[i - 1]; echo ' '
tput cup $[Lin + 1] $[i - 1]; echo ' '
tput cup $[Lin + 2] $[i - 1]; echo ' '
tput cup $[Lin + 3] $[i - 1]; echo ' '
tput cup $[Lin + 4] $[i - 1]; echo ' '
tput cup $[Lin + 5] $[i - 1]; echo ' '
tput cup $Lin $i; echo '\____/'
tput cup $[Lin + 1] $i; echo ' \ /'
tput cup $[Lin + 2] $i; echo ' \/'
tput cup $[Lin + 3] $i; echo ' ||'
tput cup $[Lin + 4] $i; echo ' ||'
tput cup $[Lin + 5] $i; echo ' (__)'
tput cup $Lin $[Fim - i - 5]; echo ' '
tput cup $[Lin + 1] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 2] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 3] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 4] $[Fim - i - 5]; echo ' '
tput cup $[Lin + 5] $[Fim - i - 5]; echo ' '
tput cup $Lin $[Fim - i - 6]; echo '\____/'
tput cup $[Lin + 1] $[Fim - i - 6]; echo ' \ /'
tput cup $[Lin + 2] $[Fim - i - 6]; echo ' \/'
tput cup $[Lin + 3] $[Fim - i - 6]; echo ' ||'
tput cup $[Lin + 4] $[Fim - i - 6]; echo ' ||'
tput cup $[Lin + 5] $[Fim - i - 6]; echo ' (__)'
Cab
done
for ((f=0; f<5; f++))
{
tput flash
sleep 0.02
}
while true
do
((++Conta % 6)) || ApagaAcende
FazBolha
Cab
sleep 0.05
y=0
for Sai in 2 4 6 6
do
let y++
C1=$[Sai == 2?$[Meio + 1]:$[Sai == 4?Meio - 0:Meio - 1]]
C2=$[Sai == 2?$[Meio + 7]:$[Sai == 4?Meio + 6:Meio + 5]]
for ((j=1; j<=Sai; j++))
{
Trab="$Trab"$(((Sai == 4)) && echo -n _ || echo -n ' ')
}
tput cup $[Lin + 2 - y] $C1
echo "$Trab"
tput cup $[Lin + 2 - y] $C2
echo "$Trab"
Trab=
done
Cab
sleep 0.05
done
==== ave ====
$ cat ave
avestruz
ave-do-paraíso
trave
cavei
traveco
==== bb ====
$ cat bb
Eu vi um velho com um fole velho nas costas. Tanto fede o fole do velho, quanto o velho do fole fede.
Um desafio: diga isso bem rápido!
==== bdb ====
$ cat bdb
#
# Avisa que determinada usuaria se conectou - versao 2
#
MandaMail=
if [ "$1" = -m ]
then
Eu=`who am i | cut -f1 -d" "`
MandaMail=1
shift
fi
if [ "$#" -ne 1 ]
then
echo "Erro -> Uso: bdb [-m] usuario"
echo " -m manda aviso via mail"
exit 1
fi
until who | grep $1 > /dev/null
do
sleep 30
done
if [ "$MandaMail" ]
then
echo "$1 se logou" | mail $Eu
else
echo "$1 se logou"
fi
==== besteira.txt ====
$ cat besteira.txt
Eu vi um velho com um fole velho nas costas . Tanto fede o fole do velho,quanto o velho do fole fede.
Um desafio :diga isso bem rápido !
==== bronze ====
$ cat bronze
#
# Lista multiplos de 11 a partir de 11 ate 99 - Versco 2
#
i=1
while [ $i -le 9 ]
do
echo $i$i
i=`expr $i + 1`
done
==== c3e1 ====
$ cat c3e1
#!/bin/bash
#
# Capitulo 3 exercicio 1
#
grep ^.*" "${1}" ".* telefones
==== c3e2 ====
$ cat c3e2
#!/bin/bash
#
# Capitulo 3 exercicio 2
#
fgrep "("$1")" telefones
==== c3e3 ====
$ cat c3e3
#!/bin/bash
#
# Capitulo 3 exercicio 3
#
Data=`date "+%b %e"`
who | grep -v "$Data"
==== c4e1 ====
$ cat c4e1
#!/bin/bash
hh=`date "+%H"` # Horas em hh
mm=`date "+%M"` # Minutos em mm
ap=am # am ou pm em ap
if [ "$hh" -gt 12 ]
then
hh=`expr $hh - 12`
ap=pm
fi
echo $hh:$mm $ap
exit
==== c4e2 ====
$ cat c4e2
#!/bin/bash
if [ "$#" -ne 2 ] # Recebi 2 parametros?
then
echo "uso: $0
exit 1
fi
if ls $2 1>/dev/null 2>&1 # O mesmo que: __ [ -_ "$_" ] Complete os _
then
if sed $1 $2 >/tmp/$$ 2>/dev/null # Testa o status da execucao do sed
then
echo sed bem sucedido
mv /tmp/$$ $2
exit
else
echo Houve erro na passagem de parametros para o sed.
rm /tmp/$$ 2>/dev/null
exit 2
fi
else
echo Arquivo $2 nao existe
exit 3
fi
==== c4e3 ====
$ cat c4e3
#!/bin/bash
#
# Capitulo 4 exercicio 3
#
Hora=`date +%H`
case $Hora in
0? | 1[01]) echo Bom Dia
;;
1[2-7] ) echo Boa Tarde
;;
* ) echo Boa Noite
;;
esac
exit
==== c5e1 ====
$ cat c5e1
#!/bin/bash
#
# Capitulo 5 exercicio 1
#
if [ $# -ne 2 ] # Recebi 2 parametros?
then
echo "Uso: $0
exit 1
fi
# Vou testar se o $1 eh numerico (No. OL) ou nao (Nome da maquina)
# Sera que exite a OL ou Maquina informada?
if expr $1 + 1 > /dev/null 2>/dev/null
then
Reg=`grep "^$1" ArqOLs` # Estou pesquisando No. OL no inicio do registro
if [ ! "$Reg" ]
then
echo Nao conheco OL=$1
exit 2
fi
Maquina=`echo "$Reg" | cut -f2` # $Reg tem que estar entre aspas para nao perder as
else
Reg=`grep " $1 " ArqOLs` # Estou pesquisando
if [ ! "$Reg" ]
then
echo Nao conheco Site=$1
exit 3
fi
Maquina=$1
fi
Opers=`echo "$Reg" | cut -f3`
# E o arquivo? Serah que ele existe?
if ls $2 1> /dev/null 2> /dev/null
then
for Oper in $Opers
do
echo "$Oper@$Maquina < $2"
done
exit
fi
echo $2 nao existe neste diretorio
exit 4
==== c6e1 ====
$ cat c6e1
#!/bin/bash
#
# Capitulo 6 exercicio 1
#
if [ $# -ne 1 ] # Recebi 1 parametro?
then
echo "Uso: $0
exit 1
fi
# Serah que o arquivo existe?
if ls $1 > /dev/null 2>&1
then
cat ArqOLs |
while read lixo Maquina Opers
do
echo 'mail '`echo $Opers | cut -f1 -d" "`"@$Maquina < $1"
done
else
echo $1 nao existe neste diretorio
exit 2
fi
### O ultimo if e seu conteudo poderia (e deveria) ser escrito assim: ###
#
# if [ -f "$1" ]
# then
# cat ArqOLs |
# while read lixo Maquina Oper lixo
# do
# echo "mail $Oper@$Maquina < $1"
# done
# else
# echo $1 nao existe neste diretorio
# exit 2
# fi
#
###########################################################################
==== c6e2 ====
$ cat c6e2
#!/bin/bash
#
# Exercicio 6.2
#
#
clear
echo "
TRANSMISSAO DE ARQUIVOS
=======================
1 - Maquina ...
2 - Login .....
3 - Senha .....
4 - Arquivos a serem transmitidos
Informe os dados acima ... "
while true
do
tput cup 5 32
echo " "
tput cup 5 32
read maq
# A maquina existe no /etc/hosts ???
if [ "$maq" -a \( `fgrep -c " $maq " /etc/hosts` -eq 1 \) ]
then
break
else
tput cup 21 25
echo "Maquina nao definida no arquivo de hosts\007" # \007 dah BEEP
read # Soh para esperar ateh teclar
tput cup 21 25
echo " " # Limpei a linha
continue
fi
done
tput cup 7 32
read acesso
tput cup 9 32
stty -echo # Inibindo o eco do teclado
read senha
stty echo
Arquivos=
while true
do
tput cup 13 21
read Arquivo
if [ ! "$Arquivo" ]
then
tput cup 17 16
echo "Finaliza entrada de arquivos (s/n) \c"
read Sair
tput cup 17 16
echo " "
if [ `echo "$Sair" | tr S s` = s ]
then
break
else
continue
fi
fi
if ls $Arquivo > /dev/null 2>&1
then
Arquivos="$Arquivos `echo $Arquivo`"
tput bold
tput cup 21 01
echo $Arquivos
tput sgr0
else
tput cup 17 16
echo "Arquivo nao existe..."
read
tput cup 17 16
echo " "
fi
tput cup 13 21
echo " "
done
for trans in $Arquivos
do
tput cup 19 16
echo " "
tput cup 19 16
tput smso
echo "Transmitindo $trans ... "
ftp -ivn "$maq" << fimftp >> /tmp/$$
user "$acesso" "$senha"
bin
put "$trans"
bye
fimftp
done
tput cup 23 16
echo "Fim de Transmissao .... Tecle
read
tput sgr0
clear
==== c7e1 ====
$ cat c7e1
#!/bin/bash
#
# Capitulo 7 exercicio 1
#
if [ $# -lt 1 ] # Recebi pelo menos 1 parametro?
then
echo "Uso: $0
Obs. Vale metacaracteres como arqs*"
exit 1
fi
if [ ! "$MAXFILES" ]
then
MAXFILES=10
fi
Qtd=`ls $* 2> /dev/null | wc -l`
if [ "$Qtd" -eq 0 ]
then
echo Nao ha arquivos a serem deletados
exit 2
fi
if [ "$Qtd" -le "$MAXFILES" ]
then
echo "Deveria fazer rm `echo $*`"
exit
fi
if [ "$Qtd" -gt 1 ]
then
echo "Existem $Qtd Arquivos a deletar... \c"
else
echo "So existe 1 arquivo a deletar...\c"
fi
echo " Posso remover? (S/n) \c"
read sn
if [ "$sn" != n ]
then
echo "Deveria fazer rm -f `echo $*`"
exit
fi
==== c7e2 ====
$ cat c7e2
#!/usr/bin/bash
#
# Este programa chama o programa c7e2.1 que coletara os dados necessarios,
# devolvendo-os aa este, que procederah aa inclusao, exclusao ou alteracao
# necessaria.
#
export Opc=0
while [ "$Opc" -lt 1 -o $Opc -gt 4 ]
do
clear
echo "
+-----------------------------------------------------+
| |
| Programas de Manutencao de ArqOLs |
| |
+-----------------------------------------------------+
OPCAO ACAO
===== ====
1 Inclui OL em ArqOLs
2 Exclui OL de ArqOLs
3 Altera OL em ArqOLs
4 Termina
Entre Com a Opcao Desejada: \c"
read Opc
done
if [ $Opc -eq 4 ]
then
exit
fi
Reg=`c7e2.1`
echo "\n\n OL a ser \c"
case $Opc
in
1) echo "incluida\c"
;;
2) echo "excluida\c"
;;
*) echo "alterada\c"
;;
esac
echo ": ==> $Reg \n
Confirma? (S/n) \c"
read sn
if [ "$sn" = n -o "$sn" = N ]
then
exit
fi
OLinf=`echo "$Reg" | cut -f1`
case $Opc in
1) if grep "^$OLinf" ArqOLs > /dev/null
then
echo "\n\nJah existe registro referente aa OL $OLinf"
read
exit 1
fi
echo "$Reg" >> ArqOLs
sort ArqOLs > /tmp/ArqOLs$$
mv -f /tmp/ArqOLs$$ ArqOLs
;;
2) if grep "^$OLinf" ArqOLs > /dev/null
then
grep -v "^$OLinf" ArqOLs > /tmp/ArqOLs$$
mv -f /tmp/ArqOLs$$ ArqOLs
else
echo "\n\nNao existe registro referente aa OL $OLinf"
read
exit 2
fi
;;
3) if grep "^$OLinf" ArqOLs > /dev/null
then
grep -v "^$OLinf" ArqOLs > /tmp/ArqOLs$$
mv -f /tmp/ArqOLs$$ ArqOLs
echo "$Reg" >> ArqOLs
sort ArqOLs > /tmp/ArqOLs$$
mv /tmp/ArqOLs$$ ArqOLs
else
echo "\n\nNao existe registro referente aa OL $OLinf"
read
exit 2
fi
;;
esac
==== c7e2.1 ====
$ cat c7e2.1
#!/usr/bin/bash
#
# Este programa foi chamado pelo c7e2 para coletar os dados necessarios.
# As rotinas de exclusao e alteracao ainda nao foram implementadas.
#
# Repare que os blocos de programa situados entre chaves, redirecionam aa
# saida para /dev/tty, que eh a saida no terminal corrente, isto eh, o
# terminal que voce estah usando.
#
{
clear
echo "
+-----------------------------------------------------+
| |
| Programas de Manutencao de ArqOLs |
| |
+-----------------------------------------------------+"
tput cup 8 22
echo "Dados para \c"
} > /dev/tty
case $Opc in
1) {
echo Inclusao
tput cup 11 22
echo "Numero da OL: \c"
read OL
tput cup 13 22
echo "Nome da Maquina: \c"
read Maq
i=0
while [ $i -le 7 ]
do
Lin=`expr 15 + $i / 2 \* 2`
Col=`expr 22 + $i % 2 \* 30`
i=`expr $i + 1`
tput cup $Lin $Col
echo "Operador$i: \c"
read Oper
if [ ! "$Oper" ]
then
break
fi
Opers=$Opers$Oper" "
done
} > /dev/tty
echo "$OL $Maq $Opers"
exit
;;
2) echo "rotina nao implementeda" > /dev/tty
exit
;;
3) echo "rotina nao implementeda" > /dev/tty
exit
;;
esac
==== c8e1 ====
$ cat c8e1
#! /bin/bash
#
# Capitulo 8 - Exercicio 1
#
Erro () # # # Este nome eh porque a funcao pode ser usada para erros de critica
{
if [ "$#" -lt 2 -o \( "$#" -gt 3 \) ]
then
echo "Uso: $0
exit 1
fi
if [ "$#" -eq 3 ]
then
C=$3
else
Len=`expr length "$1"`
C=`expr "(" 80 - "$Len" ")" / 2`
fi
tput cup $2 $C
echo "$1\07\c"
read a < /dev/tty
tput cup $2 $C
echo " "
return
}
# Inicio do bacalho
clear
if [ "$#" -ge 2 -a \( "$#" -le 3 \) ]
then
Mens=$1
shift 1
Erro "$Mens" $* ## Se $Mens nao estiver entre aspas, dara zebra. Porque??
else
Erro "Estou passando a mensagem, a linha e a coluna" 21 20
Erro "Estou passando a mensagem e a linha sem a coluna" 21
Erro "Estou passando soh a mensagem"
fi
==== c8e2 ====
$ cat c8e2
#!/bin/bash
#
# capitulo 8 - exercicio 2
# Este exercicio soh estara correto com, no maximo, 9 parametros
#
NumArgs=$#
if [ "$NumArgs" -lt 2 ]
then
echo Nao ha parametros suficientes.
exit 1
fi
while [ "$NumArgs" -gt 0 ]
do
eval echo \$$NumArgs
NumArgs=`expr $NumArgs - 1`
done
==== carros ====
$ cat carros
Corsa-3portas 150 15.20 12.20 16068.00
Corsa-4portas 182 11.10 10.00 16928.44
Corsa-Sedan 182 11.10 10.00 17376.49
Corsa-Wagon 183 12.20 12.71 20253.45
Palio 188 9.50 10.90 19974.15
Palio-Weekend 185 11.92 10.65 21200.44
Tipo 176 11.70 11.00 18310.70
Gol 175 12.40 11.60 16960.50
Parati 173 12.20 11.31 18809.22
==== case.sh ====
$ cat case.sh
#!/bin/bash
# Recebe um código formado pela soma de 4 tipos
#+ de erro e dá as msgs correspondentes. Assim,
#+ se houveram erros tipo 4 e 2, o script receberá 6
#+ Se os erros foram 1 e 2, será passado 3. Enfim
#+ os códigos de erro seguem uma formação binária.
Bin=$(bc <<< "obase=2; $1") # Passa para binário Zeros=0000 Len=${#Bin} # Pega tamanho de $Bin Bin=${Zeros:$Len}$Bin # Preenche com zeros à esquerda # Poderíamos fazer o mesmo que foi feito acima #+ com um cmd printf, como veremos no capítulo 6 case $Bin in 1[01][01][01]) echo Erro tipo 8;;& [01]1[01][01]) echo Erro tipo 4;;& [01][01]1[01]) echo Erro tipo 2;;& [01][01][01]1) echo Erro tipo 1;;& 0000) echo Não há erro;;& *) echo Binário final: $Bin esac
==== colunador.sh ====
$ cat colunador.sh
#!/bin/bash
# Recebe parâmetros via pipe e os coloca em coluna numerando-os
Parms=$(cat -)
set $Parms
for ((i=1; i<="$#"; i++))
{
Lista=$(for ((i=1; i<="$#"; i++)); { printf "%0${##}i %s\n" $i ${!i}; })
}
echo "$Lista" | column -c $(tput cols)
==== confusao ====
$ cat confusao
cd $HOME;pwd;date;ls -la;echo $LOGNAME x${SHELL}x
==== cop.awk ====
$ cat cop.awk
#
# Conta Ocorrencias de Palavras
#
awk '{
for (w = 1; w <= NF; w++) conta[$w] ++
}
END {
for (w in conta) print conta[w], w | "sort -nr"
}' $1
==== coprocesso1.sh ====
$ cat coprocesso1.sh
#!/bin/bash
coproc { read -u ${COPROC[1]} Entrada; echo Recebi $Entrada; sleep 3; }
# Main
COPROC[1]=fff
read -u ${COPROC[0]} Saida
echo O coprocesso disse: \"$Saida\"
kill $COPROC_PID
==== cores1.sh ====
$ cat cores1.sh
#!/bin/bash
# cores1.sh - Lista cores de fonte e de fundo
#+ usando setf e setb
for ((b=0; b<=7; b++)) { tput setb 9; tput setf 9; echo -n "|" for ((f=0; f<=7; f++)) { tput setb $b; tput setf $f; echo -n " b=$b f=$f " tput setb 9; tput setf 9; echo -n "|" } echo } tput setb 9; tput setf 9
==== cores2.sh ====
$ cat cores2.sh
#!/bin/bash
# cores1.sh - Lista cores de fonte e de fundo
#+ usando setaf e setab (algumas cores
#+ diferem de setf e setb
for ((b=0; b<=7; b++)) { tput setab 9; tput setaf 9; echo -n "|" for ((f=0; f<=7; f++)) { tput setab $b; tput setaf $f; echo -n " b=$b f=$f " tput setab 9; tput setaf 9; echo -n "|" } echo } tput setab 9; tput setaf 9
==== cores3.sh ====
$ cat cores3.sh
#!/bin/bash
# cores3.sh - Lista as cores da console com bold
clear
for Modo in sgr0 bold
{
echo Em modo $([ $Modo = sgr0 ] && echo Normal || echo Bold)
eval tput $Modo
for ((Cor=0; Cor <=7; Cor++))
{
tput setf $Cor
eval printf '%"$(($(tput cols)+1))"s' | tr ' ' '█'
}
tput sgr0
}
==== cores4.sh ====
$ cat cores4.sh
#!/bin/bash
# cores4.sh - Lista as cores da console com bold
clear
for ((Cor=0; Cor <=7; Cor++))
{
for Modo in sgr0 bold
{
tput $Modo
tput setf $Cor
eval printf '%-$(tput cols)s\\n' \"-Em-modo-$([ $Modo = sgr0 ] && echo Normal || echo Bold)-\" | tr ' ' '█'
}
tput sgr0
}
==== cores.sh ====
$ cat cores.sh
#!/bin/sh
# cores.sh - mostra todas as cores do console
#+ usando escapes sequences
for letra in 0 1 2 3 4 5 6 7; do
for bold in '' ';1'; do
for fundo in 0 1 2 3 4 5 6 7; do
seq="4$fundo;3$letra"
echo "\033[$seq${bold}m $seq${bold:- } \033[m\c"
done; echo
done
done
==== cp1.sh ====
$ cat cp1.sh
coproc while read coisa
do
echo $coisa
done
==== creditos ====
$ cat creditos
Tadeu 4321.00
Silveira 123.45
Tadeu 22.34
Silveira 678.89
Miltom 7654.25
==== cripta.sed ====
$ cat cripta.sed
#!/bin/sed -f
y/12z05b7zsTumvc3aip4mXutisCxg8rycdhqbf6oCnleBZjwkMSaQZRWYNI9@LAVHUIMKPEAOJGDSBUF/FUBSDGJAEPKMIUHVAL@9INYWRZQaSMkwjZBelnCo6fbqhdcyr8gxCsituXm4pia3cvmuTszO7b50z21/
==== d ====
$ cat d
#!/bin/bash
# lista diretorios
#
# Julio Cezar Neves
#
case "$#" in
0) Dir=${PWD}
Opc="d"
;;
1) if [ $1 = '-l' ]
then
Opc="ld"
Dir=$PWD
else
Opc="d"
Dir=$1
fi
;;
*) if [ $1 = '-l' ]
then
Opc="ld"
Dir=
shift
for i in $*
do
if [ ! -d "$i" ]
then
continue
fi
Dir="${Dir}${i} "
done
else
Opc="d"
Dir=
for i in $*
do
if [ ! -d "$i" ]
then
continue
fi
Dir="${Dir}${i} "
done
fi
;;
esac
# echo $Dir ; read a
for D in $Dir
do
echo "${D}:"
ls -a $D |
{
while read Arq
do
[ "$Arq" = "." -o "(" "$Arq" = ".." ")" ] && continue
if [ -d "$D/$Arq" ]
then
echo " \c"
ls "-$Opc" "$D/$Arq"
fi
done # 2>/dev/null
}
# a=$?
# [ "$a" -ne 0 ] && echo "l: $a too many parameters";exit $a
done
exit
==== debitos ====
$ cat debitos
Miltom 2345.22
Silveira 100.00
Silveira 50.00
Miltom 2340.99
Tadeu 200.00
==== decripta.sed ====
$ cat decripta.sed
#!/bin/sed -f
y/'FUBSDGJAEPKMIUHVAL@9INYWRZQaSMkwjZBelnCo6fbqhdcyr8gxCsituXm4pia3cvmuTszO7b50z21'/'12z05b7zsTumvc3aip4mXutisCxg8rycdhqbf6oCnleBZjwkMSaQZRWYNI9@LAVHUIMKPEAOJGDSBUF'/
==== div ====
$ cat div
if [ $# -ne 3 ]
then
echo "$0: Sintaxe: $0
exit 1
fi
Divid=$1
Divis=$2
Decim=$3
Resp=`expr $Divid / $Divis`,
while [ "$Decim" -gt 0 ]
do
Divid=`expr $Divid % $Divis \* 10`
Resp=$Resp`expr $Divid / $Divis`
Decim=`expr $Decim - 1`
done
echo $Resp
==== DOS.txt ====
$ cat DOS.txt
Este arquivo
foi gerado pelo
DOS/rwin e foi
baixado por um
ftp mal feito.
==== DuLoren ====
$ cat DuLoren
#
# Meu Primeiro Script em Shell
#
echo Eu tenho `cat telefones | wc -l` telefones cadastrados
echo "Que sao:"
cat telefones
==== empregado ====
$ cat empregado
clear
if Matric=`lematric`
then
:
else
exit
fi
echo "A Matricula informada foi $Matric"
# . . . Le os outros dados do empregado
==== erreeme ====
$ cat erreeme
#
# Salvando Copia de Arquivo Antes de Remove-lo
#
if [ $# -eq 0 ]
then
echo "Erro -> Uso: $0 arq [arq] ... [arq]"
echo " O uso de metacaracteres eh permitido. Ex. erreeme arq*"
exit 1
fi
MeuDir="/tmp/$LOGNAME"
if [ ! -d $MeuDir ]
then
mkdir $MeuDir
fi
if [ ! -w $MeuDir ]
then
echo Impossivel salvar arquivos em $MeuDir. Mude permissao e tente novamente...
exit 2
fi
Erro=0
for Arq
do
if [ ! -f $Arq ]
then
echo $Arq nao existe.
Erro=3
continue
fi
DirOrig=`dirname $Arq`
if [ ! -w $DirOrig ]
then
echo Sem permissao de remover no diretorio de $Arq
Erro=4
continue
fi
if [ "$DirOrig" = "$MeuDir" ]
then
echo $Arq ficara sem copia de seguranca
rm -i $Arq
[ -f $Arq ] || echo $Arq removido
continue
fi
cd $DirOrig
pwd >> $Arq
mv $Arq $MeuDir
echo $Arq removido
done
exit $Erro
==== exclui ====
$ cat exclui
/^postfix:/d
/^hplip:/d
/^gdm:/d
/^bin:/d
/^pulse:/d
==== folha.awk ====
$ cat folha.awk
awk 'BEGIN { print "Relacao de Proventos\n" ; Titulo=" Nome: Salario: Extra: Anuenio: " }
{
for ( i = 1; i <= NF; i++ )
{
print substr (Titulo, (i - 1) * 9 + 1, 9), $i
}
printf "\n"
}' funcionarios
==== folha.for.awk ====
$ cat folha.for.awk
awk 'BEGIN { print "Relacao de Proventos\n" ; Titulo=" Nome: Salario: Extra: Anuenio: " }
{
for ( i = 1; i <= NF; i++ )
{
print substr (Titulo, (i - 1) * 9 + 1, 9), $i
}
printf "\n"
}' funcionarios
==== frutas ====
$ cat frutas
abacate
maçã
morango
pera
tangerina
uva
==== funcionario ====
$ cat funcionario
#
# Le Dados dos Funcionarios
#
clear
if Matric=`lematric`
then
: ## O dois-pontos (:) e' o Comando Nulo
else
exit
fi
echo "A Matricula informada foi $Matric"
# . . . Le os outros dados do empregado
==== funcionarios ====
$ cat funcionarios
Francisco 3245,00 430,30 32,45
Guilherme 2345,67 422,34 23,45
Lee 5210,00 234,00 52,10
Paulo 4333,33 123,45 43,33
==== getoptst.sh ====
$ cat getoptst.sh
#!/bin/sh
# Execute assim:
#
# getoptst.sh -h -Pimpressora arq1 arq2
#
# e note que as informacoes de todas as opcoes sao exibidas
#
# A cadeia 'P:h' diz que a opcao -P eh uma opcao complexa
# e requer um argumento, e que h eh uma opcao simples que nao requer
# argumentos.
while getopts 'P:h' OPT_LETRA
do
echo "getopts fez a variavel OPT_LETRA igual a '$OPT_LETRA'"
echo " OPTARG eh '$OPTARG'"
done
used_up=`expr $OPTIND - 1`
echo "Dispensando os primeiros \$OPTIND-1 = $used_up argumentos"
shift $used_up
echo "O que sobrou da linha de comandos foi '$*'"
==== grepr ====
$ cat grepr
#
# Grep recursivo
# Pesquisa a cadeia de caracteres definida em $2 a partir do diretorio $1
#
find $1 -type f -print | xargs grep -l "$2" # -type f = arquivos normais
==== hora ====
$ cat hora
Hora=`date | cut -f4 -d" " | cut -f1 -d:`
Resto=`date | cut -f4 -d" " | cut -f2- -d:`
if [ "$Hora" -gt 12 ]
then
Hora=`expr $Hora - 12`
Resto=$Resto" PM"
else
Resto=$Resto" AM"
fi
echo $Hora:$Resto
exit
==== indexauto.awk ====
$ cat indexauto.awk
awk '{
Registros [$1] = $0
Velocidades [$1] = $2
}
END {
for ( Modelo in Velocidades )
print Modelo, "\t", Velocidades[Modelo] | "sort"
}' carros
==== justifica.sed ====
$ cat justifica.sed
prompt$ chmod +x justifica.sed
prompt$ ./justifica.sed arquivo.txt > arquivo-justificado.txt
se quiser alterar, o nzmero de colunas maximo, troque todos os 65
do script pelo nzmero desejado.
se quiser usar no vim, selecione o texto com o modo visual e
:'<,'>!justifica.sed
ah! esta mensagem foi justificada por ele &:)
justifica.sed
#!/bin/sed -f
# justify.sed
#
# it gets a text already wrapped on the desired number of columns
# and add extra white spaces, from left to right, word by word,
# to justify all the lines. there is a maximum of 5 spaces to be
# inserted between the words. if this limit is reached, the line
# is not justified (come on, more than 5 is horrible). empty
# lines are ignored. btw, this comments were justified with this
# script &:)
#
# 20000715 <aurelio@conectiva.com.br>
# we'll only justify lines with less than 65 chars
/^.\{65\}/!{
# cleaning extra spaces of the line
s/^ \+//
s/ \+/ /g
s/ \+$//
# don't try to justify blank lines
/^$/b
# backup of the line
h
# spaces -> pattern
# convert series of spaces to a internal pattern `n
:s2p
s/ /`5/g
s/ /`4/g
s/ /`3/g
s/ /`2/g
s/ /`1/g
t 1space
b
# pattern -> spaces
# restore the spaces converted to the internal pattern `n
:p2s
s/`5/ /g
s/`4/ /g
s/`3/ /g
s/`2/ /g
s/`1/ /g
t check
b
# check if we've reached our right limit
# if not, continue adding spaces
:check
/^.\{65\}/!b s2p
b
# here's the "magic":
# add 1 space to the first and minor internal pattern found.
# this way, the extra spaces are always added from left to right,
# always balanced, one by one.
# right after the substitution, we'll restore the spaces and
# test if our limit was reached.
:1space
s/`1/`2/ ; t p2s
s/`2/`3/ ; t p2s
s/`3/`4/ ; t p2s
s/`4/`5/ ; t p2s
# we don't want to justify with more than 5 added spaces between
# words, so let's restore the original line
/`5/x
}
==== kadeo ====
$ cat kadeo
echo -n "$1 esta logado desde "
who | grep $1 | cut -c25-
==== lematric ====
$ cat lematric
#
# Rotina de leitura e critica de matricula
#
while true
do
tput cup 10 20
echo "Digite a Matricula:"
tput cup 10 40
read Matric
if [ ! "$Matric" ]
then
tput cup 21 35
echo "Deseja Abandonar? (S/n)"
tput cup 21 59
read SN
if [ "`echo "$SN" | tr n N`" = N ] # Se digitou n ou N virara' N
then
tput cup 21 35
echo " " # Apagando a pergunta
continue
fi
exit 1 # Abandonou o programa entao codigo de retorno = 1
fi
# . . . Rotina de verificacao de DV e Critica . . .
break
done > /dev/tty # A saida de todo o loop sera' na tela
echo $Matric
exit 0
==== listcar.awk ====
$ cat listcar.awk
awk '
BEGIN { printf "%15s %10s %9s %7s %10s\n",
"Modelo", "Vel.Max.", "0 a 100", "Cons.", "Preco" }
{ printf "%15s %7s %11s %8s %11s\n",
$1, $2, $3, $4, $5
VelM = VelM + $2 ; Pr = Pr + $5 }
END { printf "\n%7s\n%10s %7s\n%5s %10s\n",
"MEDIAS:", "Velocidade", VelM / NR, "Preco", Pr / NR }' carros
==== listdir ====
$ cat listdir
echo Os Arquivos do Diretorio Corrente Sao:
ls -l
==== listdir1 ====
$ cat listdir1
cd $1
echo Os Arquivos do Diretorio $1 Sao:
ls -l
==== lt ====
$ cat lt
#
# Lista o conteudo do arquivo de telefones
#
ContaLinha=0
clear
echo "
Nome Telefone
"
cat telefones |
while read Linha
do
if [ $ContaLinha -ge 21 ]
then
tput cup 24 28
echo "Tecle
read a < /dev/tty
if [ "$a" = X ]
then
exit
fi
clear
echo "
Nome Telefone
"
ContaLinha=0
fi
echo " $Linha"
ContaLinha=`expr $ContaLinha + 1`
done
tput cup 24 49
echo "Tecle
read a
clear
exit
==== maimin.sh ====
$ cat maimin.sh
#!/bin/sh
# Transforma arquivos com nomes em MAIUSCULAS para minusculas
#
# Testando se vc passou o diretorio como parametro
# default = diretorio corrente.
if [ $# -eq 1 ]
then
Dir=$1
else
Dir="."
fi
cd $Dir
for ArqMai in `ls | grep '^[A-Z].*$'`
do
# Da forma que eu coloquei acima todos os arquivos
# cujos nomes fossem formados somente por maiusculas.
# Se vc quiser carac especiais tb, como _ ou . fa(ss)a:
# for ArqMai in `ls | grep '^[^a-z].*$'`
ArqMin=`echo $ArqMai | tr "[A-Z]" "[a-z]"`
if [ -f "$ArqMin" ] #Existe minusculo?
then
# listando os 2 em ordem cronologica (-t) e
# pegando o + novo (head -1). Se for o Maiusculo...
[ `ls -t $ArqMai $ArqMin | head -1` -eq $ArqMai ] && mv -f $ArqMai $ArqMin
fi
done
==== medieval ====
$ cat medieval
#
# medieval - Modulo-Exemplo Da Instrucao EVAL
#
echo $# argumentos.
i=1
while [ "$i" -le $# ]
do
echo "parametro $i = \c"
eval echo \$$i
i=`expr $i + 1`
done
==== misto ====
$ cat misto
123
234
acd
342
cdr
swax
1b2c3
==== natal1.sh ====
$ cat natal1.sh
#!/bin/bash
# Versão 2.0
trap "tput reset; exit" 2
clear
tput civis
lin=2
col=$(($(tput cols) / 2))
c=$((col-1))
est=$((c-2))
cor=0
tput setaf 2; tput bold
# Montando a Árvore
for ((i=1; i<20; i+=2))
{
tput cup $lin $col
for ((j=1; j<=i; j++))
{
echo -n \*
}
let lin++
let col--
}
tput sgr0; tput setaf 3
for ((i=1; i<=2; i++))
{
tput cup $((lin++)) $c
echo 'mWm'
}
tput setaf 1; tput bold
tput cup $lin $((c - 4)); echo BOAS FESTAS
let c++
k=1
# Pendurando as bolas (da árvore, claro!)
while true; do
for ((i=1; i<=35; i++))
{
# Apagando a bola que foi ligada há 25 rodadas atras
[ $k -gt 1 ] && {
tput setaf 2; tput bold
tput cup ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]}; echo \*
unset linha[$[k-1]$i]; unset coluna[$[k-1]$i] # Mantenha limpo o vetor
}
li=$((RANDOM % 9 + 3))
ini=$((c-li+2))
fim=$((c+li+2))
co=$((RANDOM % (li-2) * 2 + 1 + ini))
tput setaf $cor; tput bold # Troca cor das bolas
tput cup $li $co
echo o
linha[$k$i]=$li
coluna[$k$i]=$co
cor=$(((cor+1)%8))
sleep 0.05
}
k=$((k % 2 + 1))
done
==== natal2.sh ====
$ cat natal2.sh
#!/bin/bash
# Versão 2.0
trap "tput reset; tput cnorm; exit" 2
clear
tput civis
lin=2
col=$(($(tput cols) / 2))
c=$((col-1))
est=$((c-2))
cor=0
tput setaf 2; tput bold
# Montando a Árvore
for ((i=1; i<20; i+=2))
{
tput cup $lin $col
for ((j=1; j<=i; j++))
{
echo -n \*
}
let lin++
let col--
}
tput sgr0; tput setaf 3
for ((i=1; i<=2; i++))
{
tput cup $((lin++)) $c
echo 'mWm'
}
tput setaf 1; tput bold
tput cup $lin $((c - 4)); echo BOAS FESTAS
tput cup $((lin + 1)) $((c - 11)); echo E muito suSHELLso em 2010
let c++
k=1
# Pendurando as bolas (da árvore, claro!)
while true; do
for ((i=1; i<=35; i++))
{
# Apagando a bola que foi ligada há 25 rodadas atras
[ $k -gt 1 ] && {
tput setaf 2; tput bold
tput cup ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]}; echo \*
unset linha[$[k-1]$i]; unset coluna[$[k-1]$i] # Mantenha limpo o vetor
}
li=$((RANDOM % 9 + 3))
ini=$((c-li+2))
fim=$((c+li+2))
co=$((RANDOM % (li-2) * 2 + 1 + ini))
tput setaf $cor; tput bold # Troca cor das bolas
tput cup $li $co
echo o
linha[$k$i]=$li
coluna[$k$i]=$co
cor=$(((cor+1)%8))
# sleep 0.05
sh=1
for l in S H E L L
do
tput cup $((lin+1)) $((c-3+sh))
echo $l
let sh++
sleep 0.01
done
}
k=$((k % 2 + 1))
done
==== natal3.sh ====
$ cat natal3.sh
#!/bin/bash
# Versão 2.0
trap "tput reset; tput cnorm; exit" 2
clear
Nome="Julio Neves" # Troque pelo seu Nome para enviar a amigos
UltLin="São os votos de "$Nome" para você e sua família"
UltCol=$[($(tput cols) - ${#UltLin}) / 2]
tput civis
lin=2
col=$(($(tput cols) / 2))
c=$((col-1))
est=$((c-2))
cor=0
tput setaf 2; tput bold
# Montando a Árvore
for ((i=1; i<20; i+=2))
{
tput cup $lin $col
for ((j=1; j<=i; j++))
{
echo -n \*
}
let lin++
let col--
}
tput sgr0; tput setaf 3
for ((i=1; i<=2; i++))
{
tput cup $((lin++)) $c
echo 'mWm'
}
tput setaf 1; tput bold
tput cup $lin $((c - 4)); echo BOAS FESTAS
tput cup $((lin + 1)) $((c - 11)); echo E muito suSHELLso em 2010
tput cup $((lin + 3)) $UltCol; echo $UltLin
let c++
k=1
# Pendurando as bolas (da árvore, claro!)
while true; do
for ((i=1; i<=35; i++))
{
# Apagando a bola que foi ligada há 25 rodadas atras
[ $k -gt 1 ] && {
tput setaf 2; tput bold
tput cup ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]}; echo \*
unset linha[$[k-1]$i]; unset coluna[$[k-1]$i] # Mantenha limpo o vetor
}
li=$((RANDOM % 9 + 3))
ini=$((c-li+2))
fim=$((c+li+2))
co=$((RANDOM % (li-2) * 2 + 1 + ini))
tput setaf $cor; tput bold # Troca cor das bolas
tput cup $li $co
echo o
linha[$k$i]=$li
coluna[$k$i]=$co
cor=$(((cor+1)%8))
# sleep 0.05
sh=1
for l in S H E L L
do
tput cup $((lin+1)) $((c-3+sh))
echo $l
let sh++
sleep 0.01
done
}
k=$((k % 2 + 1))
done
==== NatalComNeve.sh ====
$ cat NatalComNeve.sh
#!/bin/bash
# Versão 2.0
# Isso foi feito para mostrar que em shell se
# pode fazer de tudo, inclusive na tela.
#
# Autor: Julio Neves
#
trap "tput reset; tput cnorm; exit" 2
function MontaArr
{
# Monta um array Arr[$Lin$Col] (ambas com zeros à esqueda)
#+ com o caracteres que está naquela posição
local i
local l
for ((i=0; i<${#3}; i++))
{
l="${3:i:1}"
Arr[$(printf "$1%02i" $[$2+$i])]="$l:$4"
}
}
NomeIni=(Julio Neves) # Troque $NomeIni para enviar a amigos, mas
# sempre pelo menos 2 e somente 2 nomes ;)
Ano=$(($(date +%m) < 10 ? $(date +%Y) : $(date +%Y) + 1))
# Preparando nome para escrever no canto inferior direito da tela
for ((Pos=0; ;Pos++))
{
s0=${NomeIni[0]:$Pos:1}
s0=${s0:- }
s1=${NomeIni[1]:$Pos:1}
s1=${s1:- }
[[ $s0 == ' ' && $s1 == ' ' ]] && break
Nome="$Nome$s0 $s1"
}
# UltLin="São os votos de "$Nome" para você e sua família"
# UltCol=$[($(tput cols) - ${#UltLin}) / 2]
# Montando a Árvore
ColLogo=$[$(tput cols)-4]
LinLogo=$[$(tput lines)-$Pos-1]
LogoTrab=0
tput civis
lin=2
col=$(($(tput cols) / 2))
ccnev=$[col - 13]
c=$((col-1))
est=$((c-2))
cor=0
tput setab 0; clear
tput setaf 2; tput bold
for ((i=1; i<20; i+=2))
{
tput cup $lin $col
for ((j=1; j<=i; j++))
{
echo -n \*
MontaArr $lin $[col+j] \* 2
}
let lin++
let col--
}
tput sgr0; tput setab 0; tput setaf 3; tput bold
for ((i=1; i<=2; i++))
{
MontaArr $lin $[c+1] mWm 3
tput cup $((lin++)) $c
echo mWm
}
tput setab 0; tput setaf 7; tput bold
tput cup $lin $((c - 4)); echo BOAS FESTAS
MontaArr $lin $[c-3] "BOAS FESTAS" 7
tput cup $((lin + 1)) $((c - 11)); echo E muito suSHELLso em $Ano
MontaArr $((lin + 1)) $((c - 10)) "E muito suSHELLso em $Ano" 7
# tput cup $((lin + 3)) $UltCol; echo $UltLin
let c++
k=1
# Pendurando as bolas (da árvore, claro!)
while true
do
for ((i=1; i<=35; i++))
{
# Apagando a bola que foi ligada há 35 rodadas atras
[ $k -gt 1 ] && {
tput setab 0; tput setaf 2; tput bold
tput cup ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]}; echo \*
MontaArr ${linha[$[k-1]$i]} ${coluna[$[k-1]$i]} \* 2
unset linha[$[k-1]$i]; unset coluna[$[k-1]$i] # Mantenha limpo o vetor
}
li=$((RANDOM % 9 + 3))
ini=$((c-li+2))
fim=$((c+li+2))
co=$((RANDOM % (li-2) * 2 + 1 + ini))
tput setab 0; tput setaf $cor; tput bold # Troca cor das bolas
tput cup $li $co
echo o
linha[$k$i]=$li
coluna[$k$i]=$co
MontaArr $li $co o $cor
sh=1
for l in S H E L L
do
tput cup $((lin+1)) $((c-3+sh))
echo $l
let sh++
done
# Olha a neve
for ((n=0; n<15; n++))
{
[ "${nev[n]}" ] || {
nev[n]=$[RANDOM % 12 + 1]$(printf "%02i" $[RANDOM % 25 + ccnev])
}
lnev=$[nev[n] / 100]
cnev=$[nev[n] % 100]
idx=$lnev$(printf "%02i" $cnev)
Antigo=${Arr[10#$idx-100]%:*}
Antigo=${Antigo:-' '}
CorAnt=${Arr[10#$idx-100]#*:}
CorAnt=${CorAnt:-0}
tput setab 0
tput setaf $CorAnt
tput cup $[lnev-1] $[cnev-1]
echo "$Antigo"
tput setab 0; tput setaf 7; tput cup $lnev $[cnev-1]; echo .
let lnev++
nev[n]=$lnev$(printf "%02i" $cnev)
[ $lnev -gt 16 ] && {
tput setab 0; tput setaf 7; tput cup $[lnev-1] $[cnev-1]; echo " "
unset nev[n]
}
tput setaf $[n%7+1]
tput cup $[LinLogo+LogoTrab] $ColLogo
echo "${Nome:$[LogoTrab*3]:3}"
(( LogoTrab++ == Pos-1)) && {
LogoTrab=0
}
}
cor=$(((cor+1)%8))
}
k=$((k % 2 + 1))
done
==== natal.sh ====
$ cat natal.sh
#!/bin/bash
# Escrito por Leandro Santiago da Silva
# leandrosansilva@gmail.com
# Script escrito por mim em shell script, baseado num programa em c de
Victorine Viviane Mizrahi.
# Depois eu comento direito ele, mas acho que dá para entender bem.
echos_verde()
{
echo -e -n "\033[42;31;1m$*"; echo -ne "\033[m"
}
echos_marrom()
{
echo -e "\033[43;32m$*"; echo -ne "\033[m"
}
echos_borda_esq()
{
echo -e "\033[40;32m$*"; echo -ne "\033[m"
}
echos_borda_dir()
{
echo -e -n "\033[40;32m$*"; echo -ne "\033[m"
}
Natal()
{
clear
for ((i=0;i
Natal
else
echo
echo Uso: natal \
echo
echo Onde 1 \<\= altura_da_arvore \<\= 10 e 1 \<\=
altura_do_caule \<\= 5
echo
fi
else
altura=6
caule=2
Natal
fi
==== nautilus-scripts/Leia-me ====
$ cat nautilus-scripts/Leia-me
ATENÇÃO!
Os arquivos desta pastas, exceto este que você está lendo, devem:
- Ser copiados para ~/.gnome2/nautilus-scripts;
- Receber permissão de execução.
Depois disso, basta clicar com o botão direito em cima de um ou mais arquivo(s) e escolher "scripts" e clicar no script que se deseja executar sobre o(s) arquivo(s) selecionado(s).
OBS: A pasta Varios tem alguns scripts que achei na Internet. Confesso que testei a maioria, mas não todos. Coloquei-os no CD como uma fonte de inspiração para que você os use, ou os aprimorem adaptando-os às suas necessidades (coisas que só nós que usamos Software Livre podemos fazer. OBA!!!!)
==== nautilus-scripts/RootScripts/gedit_root.sh ====
$ cat nautilus-scripts/RootScripts/gedit_root.sh
#!/bin/bash
# Executa uma sessão de gedit como root.
#+ O gksudo para pegar rapidamente a senha de root
#+ caso o tempo de sudo tenha expirado.
#+ O comando executado pelo gksudo não produz nada
#+ isso foi feito para o sudo da linha seguinte ganhar
#+ o privilégio de root, sem pedir senha pela
#+ linha de comando, o que complicaria.
gksudo -u root -k -m "Informe sua senha" true
sudo gedit $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
==== nautilus-scripts/RootScripts/naut_root.sh ====
$ cat nautilus-scripts/RootScripts/naut_root.sh
#!/bin/bash
# Executa uma sessão de Nautilus como root
#+ O gksudo para pegar rapidamente a senha de root
#+ caso o tempo de sudo tenha expirado.
#+ O comando executado pelo gksudo é um echo vazio.
#+ isso foi feito para o sudo da lina seguinte ganhar
#+ o privilégio de root, sem pedir senha pela
#+ linha de comando, o que complicaria.
gksudo -u root -k -m "Informe sua senha" echo
sudo nautilus --no-desktop $NAUTILUS_SCRIPT_CURRENT_URI
==== nautilus-scripts/TratamentoImagem/convert_to_jpeg ====
$ cat nautilus-scripts/TratamentoImagem/convert_to_jpeg
#!/bin/bash
while [ $# -gt 0 ]; do
picture=$1
jpg_file=`echo "$picture" | sed 's/\.\w*$/.jpg/'`
/usr/bin/convert -quality 75 "$picture" jpeg:"$jpg_file"
shift
done
==== nautilus-scripts/TratamentoImagem/convert_to_png ====
$ cat nautilus-scripts/TratamentoImagem/convert_to_png
#!/bin/bash
while [ $# -gt 0 ]; do
picture=$1
png_file=`echo "$picture" | sed 's/\.\w*$/.png/'`
/usr/bin/convert "$picture" png:"$png_file"
shift
done
==== nautilus-scripts/TratamentoImagem/Create_Thumbnail ====
$ cat nautilus-scripts/TratamentoImagem/Create_Thumbnail
#!/bin/bash
#
# Nautilus script -> Create big Thumbnails (upto 200x200) for selected files
#
# Owner : Hans-Bernhard Tr\FCtken
# hb.truetken@htp-tel.de
#
# Licence : GNU GPL
#
# Ver :1.0 Date 06.03.2002
#
# angelehnt an: http://www-user.tu-chemnitz.de/~kbo/linux/shellskript/conv.htm
#
# Dependency : ImageMagick, GNU shell utilities
for Datei in $*
do
if [ -f $Datei ]
then
echo "Bearbeite Datei $Datei ..."
DateiName=`basename $Datei`
DirName=`dirname $Datei`/.thumbnails
convert -geometry 200x200 $Datei $DirName/$DateiName.png
fi
done
exit 0
==== nautilus-scripts/TratamentoImagem/redimen_char.sh ====
$ cat nautilus-scripts/TratamentoImagem/redimen_char.sh
#!/bin/bash
# Coleta informações para fazer redimensionamento
#+ de imagens diretamente do nautilus
#+ Autor: Julio Neves
#+ Colaboração: Luiz Carlos Silveira (aka Dom)
# Abre um xterm para executar o programa
#+ a sintaxe pode parecer estranha, mas
#+ acho que esta é a melhor forma
# xterm -T "Redimensiona Imagens" -geometry 500x500 -bg darkred -fg lightgray -fn 7x14 -e bash -c "source <(tail -n +15 $0)"
xterm -T "Redimensiona Imagens" -geometry 500x500 -bg darkred -fg lightgray -fn '-dejavu-dejavu sans mono-medium-r-*-*-*-*-*-*-*-*-*-*' -e bash -c "source <(tail -n +15 $0)"
exit 0
################Programa propriamente dito.
Verde=$(tput setaf 2; tput bold) # Valores default em verde
Norm=$(tput sgr0) # Restaura cor
clear
# Preparando o basename dos arquivos para listá-los
for Arq in "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"
do
Arqs=$(echo -e "$Arqs${Arq%%*/}\n")
done
echo Os arquivos a redimensionar são:
echo == ======== = ============= ====
column -c$(tput cols) <(echo "$Arqs") # Listando arqs em colunas
read -n1 -p "
Certo? (${Verde}S${Norm}/n): "
[[ $REPLY == [Nn] ]] && exit 1
echo
read -n1 -p "Informe se redimensionamento é:
${Verde}P${Norm} - ${Verde}P${Norm}ercentual
${Verde}A${Norm} - ${Verde}A${Norm}bsoluto
==> " Tipo
case ${Tipo^} in # Conteudo passa para maiuscula (bash 4.0)
P) echo ercentual
read -p "Informe o percentual de redução: " Val
grep -Eq '^[0-9]+$' <<< $Val || { # $Val não numérico
tput flash
read -n1 -p"Percentual inválido"
exit 1
}
Val=$Val%
;;
A) echo bsoluto
read -p "Informe a largura final da imagem: " Val
grep -Eq '^[0-9]+$' <<< $Val || {
tput flash
read -n1 -p"Largura inválida"
exit 1
}
;;
*) tput flash
read -n1 -p"Informação inválida"
exit 1
esac
read -n1 -p "
Informe a saída da imagem que vc deseja:
${Verde}D${Norm} - saída da imagem em outro ${Verde}D${Norm}iretório
${Verde}S${Norm} - saída da imagem com ${Verde}S${Norm}ufixo
${Verde}G${Norm} - saída da imagem sobre${Verde}G${Norm}ravando a inicial
==> " Saida
case ${Saida^^} in
D) echo -e '\010Outro diretório'
read -p 'Informe o diretório: ' Dir
[ -d "$Dir" ] || {
tput flash
read -n1 -p "Diretório inexistente"
exit 1
}
;;
S) echo -e '\010Sufixo'
read -p "Informe o sufixo dos arquivos (${Verde}_redim${Norm}): " Suf
Suf=${Suf:-_redim}
;;
G) echo -e '\010Sobregravando'
mogrify --resize $Val $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
exit
;;
*) read -n1 -p "Você devia ter escolhido ${Verde}D${Norm}, ${Verde}S${Norm} ou ${Verde}G${Norm}"
exit 1
esac
IFS='
' # A variável $IFS ficou só com um \n (
# Agora vamos redimensionar
for Arq in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
do
if [ ${Saida^^} = D ]
then
convert "$Arq" -resize $Val "$Dir/${Arq##*/}"
echo "$Dir/${Arq##*/}" redimensionado
else
convert "$Arq" -resize $Val "${Arq%%.*}$Suf.${Arq#*.}"
echo "${Arq%%.*}$Suf.${Arq#*.}" redimensionado
fi
done
==== nautilus-scripts/TratamentoImagem/redimen_zen.sh ====
$ cat nautilus-scripts/TratamentoImagem/redimen_zen.sh
#!/bin/bash
# Redimensiona fotos direto no Nautilus
IFS="
" # IFS passa a ser somente o new line
Tipo=$(zenity --list \
--title "Redimensiona imagens" \
--text "Informe se redimensionamento\né percentual ou absoluto" \
--radiolist --column Marque --column "Tipo" \
true Percentual false Absoluto) || exit 1
if [ $Tipo = Percentual ]
then
Val=$(zenity --entry \
--title "Redimensiona imagens" \
--text "Informe o percentual de redução" \
--entry-text 50)% || exit 1 # Concatenando % em $Val
else
Val=$(zenity --entry \
--title "Redimensiona imagens" \
--text "Informe a largura final da imagem" \
--entry-text 200)x || exit 1
fi
Var=$(zenity --list --title "Redimensiona imagens" \
--text "Escolha uma das opções abaixo" \
--radiolist --height 215 --width 390 --hide-column 2 \
--column Marque --column "" --column Opções \
false 0 "Saída da imagem em outro diretório" \
false 1 "Saída da imagem com sufixo" \
true 2 "Saída da imagem sobregravando a inicial") || exit 1
case $Var in
0) Dir=$(zenity --file-selection \
--title "Escolha diretório" \
-–directory) || exit 1 ;;
1) Suf=$(zenity --entry \
--title "Redimensiona imagens" \
--text "Informe o sufixo dos arquivos" \
--entry-text _redim) || exit 1 ;;
2) mogrify --resize $Val
"$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"
exit ;;
esac
Arqs=$(echo "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | wc -l)
# No for a seguir um echo numérico atualiza
#+ a barra de progresso e um echo seguido de um
#+ jogo-da-velha (#) atualiza o texto do cabeçalho
for Arq in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
do
echo $((++i * 100 / $Arqs))
echo "# Redimensionando $(basename $Arq)"
sleep 3
if [ $Var -eq 0 ]
then
convert "$Arq" -resize $Val "$Dir/${Arq##*/}"
else
convert "$Arq" -resize $Val "${Arq%%.*}$Suf.${Arq#*.}"
fi
done | zenity --progress \
--title "Aguarde. Em redimensionamento" \
--auto-close --auto-kill
==== nautilus-scripts/TratamentoImagem/watermark ====
$ cat nautilus-scripts/TratamentoImagem/watermark
#!/bin/bash
#
# watermark.sh
# $Id: watermark,v 1.1 2004/10/03 10:52:21 ullgren Exp $
#
# Add a defined watermark to a series of pictures
#
# Absolute Location of the Watermark file
WM="/home/hajo/data/Pics/Var/watermark.gif"
if [ ! -n "$1" ]
then
zenity --error --text "Please select Pics to be watermarked!"
exit $E_BADARGS
fi
typeset -i CNT=1
typeset -i CUR=0
(
for pic in "$@"
do
echo "#Watermarking $pic"
composite -gravity SouthEast "$WM" "$pic" "$pic"
CUR=$CNT*100/$#
echo $CUR
CNT=$CNT+1
done
) | zenity --progress --auto-close --percentage=0
==== nautilus-scripts/Varios/Archiving/archiver-unarchiver ====
$ cat nautilus-scripts/Varios/Archiving/archiver-unarchiver
#!/bin/bash -x
#
#
# Nautilus script -> Ultimate Archive Tool for Nautilus
# Compress and decompress dynamic
# Multilang
#
# Owner : Largey Patrick Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
# Co-Owner : David Westlund
# daw@wlug.westbo.se
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Dependency : zenity
# : tar, bzip2, gzip, zip
# : gunzip, bunzip2, unzip, unrar
# : Nautilus
# : unace -> http://www.winace.com/
# : and Gnu tools -> grep, sed, which, etc...
#
# Encoding UTF-8
#
# Ver: 1.40 Date 24.03.2004
# Remove gdialog and add support for zenity
#
# Ver: 1.30 Date: 04.04.2003
# Add compatibilty with Nautilus 2.x
#
# Ver: 1.21 Date 06.01.2002
# Add compatibility with Xdialog + some improvemenz in code thanks to shellscript-fr(at)debianworld.org
#
# Ver: 1.20 Date 04.01.2002
# Add decompress file witout extension or with a false extension !!yeah!!
# + some small fixes + better scripting
#
# Ver: 1.15 Date 20.10.2002
# Add check and recover action for parchive (http://parchive.sourceforge.net)
# + make a .par
#
# Ver: 1.13 Date 13.06.2002
# Add Italian from Gianluca Romito
#
# Ver: 1.12 Date 10.5.2002
# Fix Bug with "ace" format from Boris de Laage de Meux (emak(at)free.fr)
#
# Ver: 1.11 Date 22.03.2002
# Add please wait dialog in decompress mode
#
# Ver: 1.10 Date 11.03.2002
# Add possibilty default config (archiver-config script)
# Add Estonian from Tõivo Leedjärv (toivo(at)linux.ee)
#
# Ver: 1.01 Date 28.02.2002
# Bug fix (thanks Shane) Add Portuguese from Rafael Rigues (rigues(at)conectiva.com.br)
#
# Ver: 1.00 Date 27.02.2002
# Yeah ! version 1.00 (I hope is no BUG)
# Add translation in "Esperanto" from Eric (eclesh(at)pacbell.net)
# Bugfix with Unzip (space file) + German update
#
# Ver : 0.9.9-6 Date 7.2.2002
# Add idea from David (check if programm is available)
# Add rar format
#
# Ver : 0.9.9-5 Date 31.01.2002
# Bugfix with : zip a directory , is recursive yet
# Add no case sensitiv (tgz, TGZ, TgZ,...)
#
# Ver : 0.9.9-4 Date 22.01.2002
# me: Add dialog for unarchive "yes or no"
# Please test all possibility to find bug to ver 1.00
#
# Ver: 0.9.9-2 Date 21.01.2002
# me: Add .Z Format compress and uncompress
# Add .ace format to decompress
# Add Dialog for decompress to overwrite file by David
# Some correction in force to decompress
# better recognise file if archive or not
#
# Ver: 0.9.9-1 Date 20.01.2002
# me: Add script uncompress_all, please wait ....
# Add some correction by David Westlund
# make a check to find what is for file
# if file is an archive -> decompress else compress
#
# Ver: 0.9.8 Date 12.01.2002
# me: Add Dialog with compressor choice
# tar.gz, tar.bz2, zip, gz, bz2
# Please update with rar and unrar (I don't have)
#
# Ver: 0.9.4 Date: 11.05.2001
# Support for swedish
# Don't create files with names like archive.tar.gz.tar.gz or archive.tgz.tar.gz
# If the input is just one file, the archive will be called
# Added by David Westlund
#
# Ver: 0.9.3 Date: 10.09.2001
# me: added file mit space !!!
#
# Ver: 0.9.2 Date: Sept 9, 2001
# me: added confirm windows + German Support
#
# Ver: 0.9.1 Date: Sept 5, 2001
# Shane Mueller added patch from Manuel Clos to add Spanish support
#
# Ver : 0.9 Date : 11.08.2001
#
curpath=`echo $NAUTILUS_SCRIPT_CURRENT_URI | sed 's/file\:\/\///'`
if [ ! -z $curpath ]
then
cd $curpath
else
cd `pwd`
fi
#
# Default language
#
filename="File name?"
fileexist="File exists. Overwrite?"
title="Archiver-Unarchiver"
archive="archive"
compressor="extension: archive: "
decompressor="Do you want to uncompress: "
valid="available"
notvalid="not available"
pleasewait="Please wait...."
warning="Warning!"
beuh="Unknown format."
ncompr="could not be uncompressed."
compr="has been uncompressed."
rec="was created successfully."
overwrite="The following files will be overwritten: "
proceed="Do you want to proceed?"
parchive="Parchive : "
parmiss="Cannot recover, too many file missing"
parok="parity archive valid"
parnotok=" lacking, recover ?"
format="format"
info="information"
choix="choice"
case $LANG in
fr* )
filename="Nom du Fichier ?"
fileexist="Fichier existant, écraser ?"
title="Archiveur-Desarchiveur"
archive="archive"
decompressor="Voulez vous désarchiver : "
compressor="Extension de l'archive : "
valid="disponible"
notvalid="non disponible"
pleasewait="Veuillez patientez ....."
warning="! Attention !"
beuh="format inconnu."
ncompr="ne peut être décompressé."
compr="est décompressé."
rec="est enregistré."
overwrite="les fichiers suivant seront écrasé: "
proceed="Voulez-vous poursuirvre ?"
parchive="Parchive : "
parmiss="Impossible de reconstruire, trop de fichier manquant."
parok="archive de parité valide."
parnotok=" manquant, reparez ?"
format="extension"
info="information"
choix="choice";;
es* )
filename="¿Nombre del archivo?"
fileexist="El archivo ya existe, ¿sobreescribir?"
title="Archivar"
archive="archivo"
compressor="¿extensión del archivo?"
decompressor="¿ Quiere descomprimir "
valid="disponible"
notvalid="no disponible"
pleasewait="Por favor, espere..."
warning="¡ Cuidado !"
beuh="Formato desconocido"
ncompr="no se puede descomprimir"
compr="se descomprimió correctamente."
rec="se creó correctamente"
overwrite="los archivos suiguientes serán sobreescritos: "
proceed="¿ Quiere continuar ?" ;;
de* )
filename="Dateiname ?"
fileexist="Datei existiert bereits, überschreiben ?"
title="Archiver-Desarchiver"
archive="archiv"
compressor="Extension von Archiv : "
decompressor="wollen Sie dekomprimieren : "
valid="Gültig"
notvalid="Nicht gültig"
pleasewait="Bitte warten ...."
warning="! Warnung !"
beuh="unbekanntes Format"
ncompr="kann nicht dekomprimieren"
compr="ist komprimiert"
rec="ist gespeichert"
overwrite="soll(en) diese Datei(en) überschriebenerden: "
proceed="Wollen Sie weitermachen ?" ;;
eo* )
filename="Dosiera nomo?"
fileexist="Dosiero ekzistas. Æu superskribu?"
title="Ar¶igilo-Malar¶ivigilo"
archive="ar¶ivo"
compressor="Fina¼o de la ar¶ivo?"
decompressor="Æu vi volas malar¶ivigi: "
valid="havebla"
notvalid="nehavebla"
pleasewait="Bonvolu atendi..."
warning="Avertu!"
beuh="Nekonata formato"
ncompr="Ne povis kompresigi"
compr="estas kompresigita"
rec="øuste kreita"
overwrite="La sekvantaj dosieroj superskribiøos: "
proceed="Æu vi volas procedi?";;
pt* )
filename="Nome do arquivo?"
fileexist="O arquivo já existe. Sobrescrever?"
title="Compactador-Descompactador"
archive="arquivo"
compressor="extensão: arquivo: "
decompressor="Você quer descompactar: "
valid="disponível"
notvalid="não disponível"
pleasewait="Aguarde...."
warning="Aviso!"
beuh="Formato desconhecido."
ncompr="não pôde ser descompactado."
compr="foi descompactado."
rec="foi criado com sucesso."
overwrite="Os seguintes arquivos serão sobrescritos: "
proceed="Deseja continuar?" ;;
sv* )
filename="Filnamn?"
fileexist="Filen existerar, vill du skriva över?"
title="tar.gz-arkiverare"
compressor="Filändelse arkiv :"
decompressor="Vill du packa upp : "
archive="arkiv"
#valid="????"
#notvalid="????"
pleasewait="Var god vänta..."
warning="! Varning !"
beuh="Okänt format"
ncompr="kunde inte packas upp korrekt"
compr="är uppackad"
rec="är sparad"
overwrite="Följande filer kommer skrivas över: "
proceed="Vill du fortsätta?" ;;
et* )
filename="Faili nimi?"
fileexist="Fail on juba olemas. Kas kirjutada üle?"
title="Arhivaator"
archive="arhiiv"
compressor="laiend: arhiiv: "
decompressor="Kas sa tahad lahti pakkida: "
valid="võimalik"
notvalid="ei ole võimalik"
pleasewait="Palun oota...."
warning="Hoiatus!"
beuh="Tundmatu vorming."
ncompr=": ei saa lahti pakkida."
compr="lahti pakitud."
rec="edukalt loodud."
overwrite="Järgnevad failid kirjutatakse üle: "
proceed="Kas tahad jätkata?" ;;
it* )
filename="Nome File?"
fileexist="Il file esiste. Sovrascriverlo?"
title="Compressore Decompressore"
archive="archivio"
compressor="estensione: archivio: "
decompressor="Vuoi decomprimere: "
valid="disponibile"
notvalid="non disponivile"
pleasewait="Attendere per favore...."
warning="Attenzione!"
beuh="Formato sconosciuto."
ncompr="non puo' essere decompresso."
compr="e' stato decompresso."
rec="e' stato creato con successo."
overwrite="I seguenti files saranno sovrascritti: "
proceed="Vuoi procedere?" ;;
esac
#
# check the config file
#
if [ ! -f ~/.archiver.conf ]
then echo "" > ~/.archiver.conf
fi
#
# Fonction
#
pleasewait() {
zenity --title "$title" --info --text "$pleasewait" --width 200 --height 25&
dialogpid=$!
}
#
# Fonction decompress
#
tardec() {
fto=`ls -d --color=never \`tar -tf "$1" | sed 's/ /\?/g'\` 2>&1 | grep -v "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
tar -xf "$1" || error=1
else
exit 0
fi
else
pleasewait
tar -xf "$1" || error=1
fi
}
targzdec() {
fto=`ls -d --color=never \`tar -ztf "$1" | sed 's/ /\?/g'\` 2>&1 | grep -v "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
tar -xzf "$1" || error=1
else
exit 0
fi
else
pleasewait
tar -xzf "$1" || error=1
fi
}
tarbzip2dec() {
fto=`ls -d --color=never \`tar -jtf "$1" | sed 's/ /\?/g'\` 2>&1 | grep -v "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
tar -jxf "$1" || error=1
else
exit 0
fi
else
pleasewait
tar -jxf "$1" || error=1
fi
}
gzdec() {
fto=`ls -d --color=never \`echo "$1" | sed 's/.gz//'\` 2>&1 | grep -v -e "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
gunzip -fN "$1" || error=1
else
exit 0
fi
else
pleasewait
gunzip -N "$1" || error=1
fi
}
bzip2dec() {
fto=`ls -d --color=never \`echo "$1" | sed 's/.bz2//'\` 2>&1 | grep -v -e "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text"$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
bunzip2 -fk "$1" || error=1
else
exit 0
fi
else
pleasewait
bunzip2 -k "$1" || error=1
fi
}
zipdec() {
fto=`ls -d --color=never \`zipinfo -1 "$1" | sed 's/ /\?/g'\` 2>&1 | grep -v -e "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
unzip -o "$1" || error=1
else
exit 0
fi
else
pleasewait
unzip -o "$1" || error=1
fi
}
rardec() {
fto=`ls -d --color=never \`rar l "$1" | gawk '/2.0$/{ print $1 }'\` 2>&1 | grep -v -e "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
unrar x -kb -o+ "$1" || error=1
else
exit 0
fi
else
pleasewait
unrar x -kb -o+ "$1" || error=1
fi
}
zdec() {
fto=`ls -d --color=never \`zcat -l "$1" | gawk '/%/{ print $4 }'\` 2>&1 | grep -v -e "^ls"`
if [ ! -z "$fto" ]
then
if zenity --title "$title" --question --text "$overwrite \n$fto\n$proceed" --width 200 --height 25
then
pleasewait
uncompress -f "$1" || error=1
else
exit 0
fi
else
pleasewait
uncompress "$1" || error=1
fi
}
acedec() {
pleasewait
unace x "$1" || error=1
}
#
# test archive or not
#
test_parity=`echo "$1" | grep [.][pP][aA][rR]$`
test_arch1=`file -b "$1" | grep -v 'PARity' | grep 'archive'`
test_arch2=`file -b "$1" | grep 'compress'`
test_arch3=`echo "$1" | grep [.][aA][cC][eE]$`
test_arch="$test_arch1$test_arch2$test_arch3"
if [ ! -z "$test_arch" ]
then
#
# is one archive -> decompress
#
allfiles=`echo $@ | sed 's/\ /\\n/g'`
decompressed=""
error=0
if zenity --title "$title" --question --text "$decompressor \n\n$allfiles ?\n" --width 200 --height 25
then
while [ $# -gt 0 ]
do
if
echo "$1" | grep -i '\.tar\.gz$' 2>&1
then
targzdec "$1"
elif
echo "$1" | grep -i '\.tgz$' 2>&1
then
targzdec "$1"
elif
echo "$1" | grep -i '\.tar$' 2>&1
then
tardec "$1"
elif
echo "$1" | grep -i '\.gz$' 2>&1
then
gzdec "$1"
elif
echo "$1" | grep -i '\.tar\.bz2$' 2>&1
then
tarbzip2dec "$1"
elif
echo "$1" | grep -i '\.bz2$' 2>&1
then
bzip2dec "$1"
elif
echo "$1" | grep -i '\.zip$' 2>&1
then
zipdec "$1"
elif
echo "$1" | grep -i '\.rar$' 2>&1
then
rardec "$1"
elif
echo "$1" | grep -i '\.z$' 2>&1
then
zdec "$1"
elif
echo "$1" | grep -i '\.ace$' 2>&1
then
acedec "$1"
#
# Decompress if file is an archive with no extension and test what is for archive type
#
else
ifnoextension=`file -b "$1" | gawk '/compress/{ print $1 }'`
ifnoextensiona=`file -b "$1" | gawk '/archive/{ print $1 }'`
if [ "$ifnoextension" = "bzip2" ]
then
if tar -tjf "$1" 2>/dev/null
then tarbzip2dec "$1"
else bzip2dec "$1"
fi
elif [ "$ifnoextension" = "gzip" ]
then
if tar -tzf "$1" 2>/dev/null
then targzdec "$1"
else gzdec "$1"
fi
elif [ "$ifnoextension" = 'compress'\''d' ]
then
zdec "$1"
elif [ "$ifnoextensiona" = "GNU" ]
then
tardec "$1"
elif [ "$ifnoextensiona" = "Zip" ]
then
zipdec "$1"
elif [ "$ifnoextensiona" = "RAR" ]
then
rardec "$1"
else
zenity --title "$title" --warning --text "$1 $beuh $noextension" --width 200 --height 25
fi
fi
#
# End script for decompression
#
if [ $error = 0 ]
then
decompressed="$decompressed $1\n"
fi
if [ $error = 1 ]
then
zenity --title "$title" --warning --text "$1 $beuh $noextension" --width 200 --height 25
fi
kill $dialogpid
shift
done
else
exit 0
fi
if [ ! -z "$decompressed" ]
then
zenity --title "$title" --info --text "$decompressed $compr" --width 200 --height 25
fi
#
# parity test or recovery
#
elif [ ! -z "$test_parity" ]
then
parbinary=`which par || which parchive`
testpar=`$parbinary c "$1" 2>&1 | gawk '/NOT FOUND/{ print $1 }'`
testrecover=`$parbinary c "$1" 2>&1 | grep "Too many missing files:"`
if [ -z "$testpar" ]
then zenity --title "$title" --info --text "$parchive$parok" --width 200 --height 25
else
if zenity --title "$title" --question --text "$parchive$testpar$parnotok" --width 200 --height 25
then
if [ -z "$testrecover" ]
then
pleasewait
$parbinary r "$1"
kill $dialogpid
else
zenity --title "$title" --warning --text "$parmiss" --width 200 --height 25
fi
else
exit 0
fi
fi
else
#
# test if programm are availlable
#
listcompprg="tar zip gzip bzip2 rar compress"
for u in $listcompprg
do
if which $u 2>/dev/null
then
eval a$u="$valid"
else
eval a$u="$notvalid"
fi
done
if which par 2> /dev/null || which parchive 2> /dev/null
then
apar="$valid"
else
apar="$notvalid"
fi
#
# is not one archive -> compress
#
if [ $# = 1 ]
then
archive="$1"
fi
if
nom=`zenity --title "$title" --entry --text "$filename" --entry-text "$archive" --width 200 --height 25 2>&1`
then
if [ ! -d "$1" -a $# = 1 ]
then
configsingle=`cat ~/.archiver.conf | gawk '/single/{ print $2 }'`
if [ -z "$configsingle" ]
then
compres=`zenity --title "$title" --list --radiolist --column "$choix" --column "$format" --column "$info" --text "$compressor" FALSE ".zip" "$azip" TRUE ".gz" "$agzip" FALSE ".bz2" "$abzip2" FALSE ".Z" "$acompress" FALSE ".rar" "$arar" FALSE ".par" "$apar" --width 200 --height 220 2>&1`
else
compres="$configsingle"
fi
else
configmulti=`cat ~/.archiver.conf | gawk '/multi/{ print $2}'`
if [ -z "$configmulti" ]
then
compres=`zenity --title "$title" --list --radiolist --column "$choix" --column "$format" --column "$info" TRUE ".tar.gz" "$agzip" FALSE ".tar.bz2" "$abzip2" FALSE ".zip" "$azip" FALSE ".tar" "$atar" FALSE ".rar" "$arar" FALSE ".par" "$apar" --width 200 --height 220 2>&1`
else
compres="$configmulti"
fi
fi
compres=`echo $compres | sed 's/\"//g'`
nom="${nom%$compres}"
if [ ! -z "$compres" ]
then
while [ -f ./"$nom"$compres ]
do
if zenity --title "$title" --question --text "$fileexist" --width 200 --height 25
then
rm -f ./"$nom"$compres
else
if zenity --title "$title" --entry --text "$filename" --entry-text "$archive" --width 200 --height 25
then
continue
else
exit 0
fi
fi
done
else
exit 0
fi
pleasewait
case $compres
in
.tar.gz )
while [ $# -gt 0 ]
do
if [ -f ./"$nom".tar ]
then
tar -rf ./"$nom".tar "$1"
else
tar -cf ./"$nom".tar "$1"
fi
shift
done
gzip -f -9 ./"$nom".tar ;;
.tar.bz2 )
while [ $# -gt 0 ]
do
if [ -f ./"$nom".tar ]
then
tar -rf ./"$nom".tar "$1"
else
tar -cf ./"$nom".tar "$1"
fi
shift
done
bzip2 -f -9 ./"$nom".tar ;;
.zip )
while [ $# -gt 0 ]
do
if [ -f ./"$nom".zip ]
then
zip -r -9 ./"$nom".zip "$1"
else
zip -r -u -9 ./"$nom".zip "$1"
fi
shift
done ;;
.tar )
while [ $# -gt 0 ]
do
if [ -f ./"$nom".tar ]
then
tar -rf ./"$nom".tar "$1"
else
tar -cf ./"$nom".tar "$1"
fi
shift
done ;;
.gz )
while [ $# -gt 0 ]
do
gzip -cN -9 "$1" >> ./"$nom".gz
shift
done ;;
.rar )
while [ $# -gt 0 ]
do
rar a -r0 "$nom".rar "$1"
shift
done ;;
.bz2 )
bzip2 -c -9 "$1" >> ./"$nom".bz2 ;;
.Z )
compress -c "$1" >> ./"$nom".Z ;;
.par )
parbinary=`which par || which parchive`
rm "$nom".p[0-9][0-9]
$parbinary a "$nom".par "$@";;
* )
echo "error" ;;
esac
kill $dialogpid
sleep 1
zenity --title "$title" --info --text "$PWD/$nom$compres $rec" --width 200 --height 25
else
exit 0
fi
fi
==== nautilus-scripts/Varios/Archiving/Compress__.bz2_ ====
$ cat nautilus-scripts/Varios/Archiving/Compress__.bz2_
#!/bin/sh
#
# BZIP2 wrapper for Nautilus Scripts menu.
#
# AUTHOR: Roberto Piscitello
# VERSION: 1.1
# LICENSE: public domain
# DEPENDENCIES: Nautilus, nautilus-error-dialog | gdialog | xmessage, bzip2
# CHANGES:
# v1.1: 17 Mar 2002
# * made public domain (no more GPL)
# * removed beep stuff, since it doesn't seem to work
# * added nautilus-error-dialog support
# * use "which" to avoid hardcoded paths (as suggested by Dylan Griffiths)
# v1.0: 21 May 2001
# * first public release
# INSTALL NOTES:
# * open a Nautilus window and select, from the menu, File->Script->Open Scripts directory.
# * copy this file in that directory.
# * right-click on the copied file and open the Properties window.
# * from the first tab: (if you want) change its icon (I suggest
# "/usr/share/pixmaps/nautilus/gnome-compressed.png") and name.
# * from the third tab: give executable permissions to the file owner.
#
TMP_FILE=`tempfile 2> /dev/null` || TMP_FILE="/tmp/nautilus-script.$$"
IFS="
"
trap "rm -f $TMP_FILE" EXIT
for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
cd `dirname $F`
if ! bzip2 `basename $F` 2> $TMP_FILE; then
# Some error happened: show an error message
if which nautilus-error-dialog; then
nautilus-error-dialog --title bzip2 --message "`cat $TMP_FILE`."
elif which gdialog; then
gdialog --title bzip2 --msgbox "`cat $TMP_FILE`." 20 100
elif which xmessage; then
xmessage -buttons OK -file $TMP_FILE
fi
fi
done
==== nautilus-scripts/Varios/Archiving/Compress__.gz_ ====
$ cat nautilus-scripts/Varios/Archiving/Compress__.gz_
#!/bin/sh
#
# GZIP wrapper for Nautilus Scripts menu.
#
# AUTHOR: Roberto Piscitello
# VERSION: 1.1
# LICENSE: public domain
# DEPENDENCIES: Nautilus, nautilus-error-dialog | gdialog | xmessage, gzip
# CHANGES:
# v1.1: 17 Mar 2002
# * made public domain (no more GPL)
# * removed beep stuff, since it doesn't seem to work
# * added nautilus-error-dialog support
# * use "which" to avoid hardcoded paths (as suggested by Dylan Griffiths)
# v1.0: 21 May 2001
# * first public release
# INSTALL NOTES:
# * open a Nautilus window and select, from the menu, File->Script->Open Scripts directory.
# * copy this file in that directory.
# * right-click on the copied file and open the Properties window.
# * from the first tab: (if you want) change its icon (I suggest
# "/usr/share/pixmaps/nautilus/gnome-compressed.png") and name.
# * from the third tab: give executable permissions to the file owner.
#
TMP_FILE=`tempfile 2> /dev/null` || TMP_FILE="/tmp/nautilus-script.$$"
IFS="
"
trap "rm -f $TMP_FILE" EXIT
for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
cd `dirname $F`
if ! gzip `basename $F` 2> $TMP_FILE; then
# Some error happened: show an error message
if which nautilus-error-dialog; then
nautilus-error-dialog --title gzip --message "`cat $TMP_FILE`."
elif which gdialog; then
gdialog --title gzip --msgbox "`cat $TMP_FILE`." 20 100
elif which xmessage; then
xmessage -buttons OK -file $TMP_FILE
fi
fi
done
==== nautilus-scripts/Varios/Archiving/Decompress ====
$ cat nautilus-scripts/Varios/Archiving/Decompress
#!/bin/sh
#
# GUNZIP and BUNZIP2 wrapper for Nautilus Scripts menu.
#
# AUTHOR: Roberto Piscitello
# VERSION: 1.1
# LICENSE: public domain
# DEPENDENCIES: Nautilus, nautilus-error-dialog | gdialog | xmessage, gzip, bzip2, awk
# CHANGES:
# v1.1: 17 Mar 2002
# * made public domain (no more GPL)
# * removed beep stuff, since it doesn't seem to work
# * added nautilus-error-dialog support
# * use "which" to avoid hardcoded paths (as suggested by Dylan Griffiths)
# v1.0: 21 May 2001
# * first public release
# INSTALL NOTES:
# * open a Nautilus window and select, from the menu, File->Script->Open Scripts directory.
# * copy this file in that directory.
# * right-click on the copied file and open the Properties window.
# * from the first tab: (if you want) change its icon (I suggest
# "/usr/share/pixmaps/nautilus/gnome-compressed.png") and name.
# * from the third tab: give executable permissions to the file owner.
#
TMP_FILE=`tempfile 2> /dev/null` || TMP_FILE="/tmp/nautilus-script.$$"
IFS="
"
trap "rm -f $TMP_FILE" EXIT
for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
cd `dirname $F`
if [ `echo $F|awk '{ print substr($0,length($0)-2) }'` = "bz2" -o `echo $F|awk '{ print substr($0,length($0)-1) }'` = "bz" ]; then
UZIP="bunzip2"
else
UZIP="gunzip"
fi
if ! $UZIP `basename $F` 2> $TMP_FILE; then
# Some error happened: show an error message
if which nautilus-error-dialog; then
nautilus-error-dialog --title $UZIP --message "`cat $TMP_FILE`."
elif which gdialog; then
gdialog --title $UZIP --msgbox "`cat $TMP_FILE`." 20 100
elif which xmessage; then
xmessage -buttons OK -file $TMP_FILE
fi
fi
done
==== nautilus-scripts/Varios/Archiving/gnome-archive ====
$ cat nautilus-scripts/Varios/Archiving/gnome-archive
#!/bin/sh
##This invokes the Gnome Archiver (meatgrinder) with the selected files
##meat-grinder is a gnome-base graphical tar.gz creator.
meat-grinder $@
==== nautilus-scripts/Varios/Archiving/super-extractor ====
$ cat nautilus-scripts/Varios/Archiving/super-extractor
#!/bin/bash
# This script tests the file type of the file then extracts
# it with the correct program. If the program supports it,
# it will prompt you for a directory to extract it to.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Keith Conger
#
# Install in your ~/Nautilus/scripts directory.
# You need to be running Nautilus 1.0.3+, gnome-utils, unrar,
# unace, unarj and unzip. The rest should already be installed.
DEFAULT_DIR=~/tmp/
UNRAR_PATH=/usr/local/bin #Path to unrar binary.
UNZIP_PATH=/usr/bin #Path to unzip binary.
UNACE_PATH=/usr/local/bin #Path to unace binary.
UNARJ_PATH=/usr/bin #Path to unarj binary.
BUNZIP2_PATH=/usr/bin #Path to bzip2 binary.
GUNZIP_PATH=/usr/bin #Path to gunzip binary.
TAR_PATH=/bin #Path to tar binary.
FILE_TYPE=$(file -b $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|awk '{ print $1}')
MIME_TYPE=$(file -b $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS)
if [ "$FILE_TYPE" = "bzip2" ]; then
TAR_TEST=$(echo $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|grep .tar.)
if [ $TAR_TEST = $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then
$BUNZIP2_PATH/bzcat $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|tar xv >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
else
$BUNZIP2_PATH/bunzip2 -d $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
fi
elif [ "$FILE_TYPE" = "RAR" ]; then
DIR=$(gdialog --title "Extract compressed file to..." --inputbox "Directory to extract to:" 200 400 "$DEFAULT_DIR" 2>&1)
mkdir $DIR
$UNRAR_PATH/unrar x -kb $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $DIR/ >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
elif [ "$FILE_TYPE" = "Zip" ]; then
DIR=$(gdialog --title "Extract compressed file to..." --inputbox "Directory to extract to:" 200 400 "$DEFAULT_DIR" 2>&1)
mkdir $DIR
$UNZIP_PATH/unzip $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS -d $DIR/ >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
elif [ "$FILE_TYPE" = "gzip" ]; then
TAR_TEST=$(echo $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|grep .tar.)
if [ $TAR_TEST = $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then
TAR="1"
fi
TAR_TEST=$(echo $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|grep .tgz)
if [ $TAR_TEST = $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then
TAR="1"
fi
if [ $TAR = 1 ]; then
$TAR_PATH/tar zxvf $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
else
$GUNZIP_PATH/gunzip $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
fi
elif [ "$FILE_TYPE" = "ARJ" ]; then
$UNARJ_PATH/unarj x $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
elif [ "$FILE_TYPE" = "ACE" ]; then
$UNACE_PATH/unace x -y $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
elif [ "$FILE_TYPE" = "GNU" ]; then
$TAR_PATH/tar xvf $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> /tmp/extract-script.log
gdialog --separate-output --title "Extraction Log" --textbox /tmp/extract-script.log 50 70 2>&1
rm /tmp/extract-script.log
else
echo -e "\007"
gdialog --separate-output --title "File error" --msgbox " File $1 is not a known archive type. File type reported as: $MIME_TYPE " 50 100 2>&1
fi
==== nautilus-scripts/Varios/Archiving/unrar ====
$ cat nautilus-scripts/Varios/Archiving/unrar
#!/bin/sh
#
# This script unrars to a directory specified in gdialog and
# redirects stdout to a log file.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Keith Conger
#
# Install in your ~/Nautilus/scripts directory.
# You need to be running Nautilus 1.0.3 +
UNRAR_PATH=/usr/local/bin #Path to unrar binary.
DIR=$(gdialog --title "unrar to..." --inputbox "unrar to..." 200 350 ~/tmp/"$1" 2>&1)
mkdir $DIR
$UNRAR_PATH/unrar x -kb "$1" $DIR/ >> $DIR/"$1".log
gdialog --separate-output --title "unrar log" --textbox $DIR/"$1".log 50 70 2>&1
rm $DIR/"$1".log
==== nautilus-scripts/Varios/Execute/command_prompt_here ====
$ cat nautilus-scripts/Varios/Execute/command_prompt_here
#!/usr/bin/env python
# Open command prompt in a single selected directory
# or otherwise in current dir
# Put this (executable) file in ~/.gnome2/nautilus-scripts/
# Then right click a directory or anywhere in current dir window
# to get the scripts->command_prompt_here menu option
# This has been tested on nautilus 2.2 and 2.4
def nautilus_script_display_error():
"""This is a general error message display for nautilus scripts"""
import sys
#errors_fd,errors_name=tempfile.mkstemp() #This not available until python 2.3
errors_name=os.tmpnam()
errors_fd=file(errors_name,"w")
etype, emsg, etb = sys.exc_info()
errors_fd.write('line '+str(etb.tb_lineno)+': '+str(etype)+': '+str(emsg)+'\n')
errors_fd.write('\n$PWD: %s' % os.getcwd())
errors_fd.write('\nsys.argv: %s' % str(sys.argv[1:]))
for var in os.environ:
if var.startswith("NAUTILUS_"):
errors_fd.write("\n%s: %s" % (var,os.environ[var].replace('\n',"\\n")))
errors_fd.close()
pid = os.fork()
if pid == 0:
cmd = ["zenity", "--text-info", "--filename=%s" % errors_name, "--title=error", "--width=640", "--height=220"]
os.execvp(cmd[0],cmd)
os.waitpid(pid,0)
os.unlink(errors_name)
import os
import urllib, urlparse
try:
home_dir=os.environ["HOME"]
# An alternative to below could be:
# 1. get where we are (CURRENT_URI (file://, trash:, x-nautilus-desktop:///))
# 2. use argv to see if 1 selected dir under that?
dir_to_open=""
selected=os.environ["NAUTILUS_SCRIPT_SELECTED_URIS"].split("\n")[:-1]
#Note getting SELECTED_URIS rather than SELECTED_FILE_PATHS as later
#is not set when ~/Desktop and ~/.Trash selected??
if len(selected) == 1:
uri_bits=urlparse.urlparse(urllib.unquote(selected[0]))
if uri_bits[0] == "file":
dir_to_open=uri_bits[2]
elif uri_bits[0] == "x-nautilus-desktop":
if uri_bits[2] == "///trash":
dir_to_open=home_dir+'/.Trash'
elif uri_bits[2] == "///home":
dir_to_open=home_dir+'/Desktop'
if not os.path.isdir(dir_to_open):
dir_to_open=""
if not dir_to_open: #we didn't select 1 directory so open current dir
current_uri=os.environ["NAUTILUS_SCRIPT_CURRENT_URI"]
uri_bits=urlparse.urlparse(urllib.unquote(current_uri))
if uri_bits[0] == "file":
dir_to_open=uri_bits[2]
elif uri_bits[0] == "x-nautilus-desktop":
dir_to_open=home_dir+'/Desktop'
elif uri_bits[0] == "trash":
dir_to_open=home_dir+'/.Trash'
shell_cmd=["gnome-terminal", "--working-directory=%s"%dir_to_open]
os.execvp(shell_cmd[0],shell_cmd)
except:
nautilus_script_display_error()
==== nautilus-scripts/Varios/Execute/gedit ====
$ cat nautilus-scripts/Varios/Execute/gedit
#!/bin/bash
#
# Nautilus script -> open gedit
#
# Owner : Largey Patrick from Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Ver. 0.9-1 Date: 16.02.2002
# Add multiple file open in the same windows
#
# Ver: 0.9 Date: 27.10.2001
# Initial release
#
# Dependence : Nautilus (of course)
# Gnome-utils (gdialog)
#
filesall=""
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\?/g'`
filesall="$files $filesall"
shift
done
gedit $filesall&
==== nautilus-scripts/Varios/Execute/ghex ====
$ cat nautilus-scripts/Varios/Execute/ghex
#!/bin/sh
#This script opens the selected file in ghex--a hex editor
#It will only open a single file
ghex $@
==== nautilus-scripts/Varios/Execute/glimmer ====
$ cat nautilus-scripts/Varios/Execute/glimmer
#!/bin/bash
#
# Nautilus script -> open glimmer
#
# Owner : Largey Patrick from Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Ver. 0.9-1 Date: 16.02.2002
# Add multiple file open in the same windows
#
# Ver: 0.9 Date: 27.10.2001
# Initial release
#
# Dependence : Nautilus (of course)
# Glimmer http://glimmer.sourceforge.net/
#
filesall=""
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\?/g'`
filesall="$files $filesall"
shift
done
glimmer $filesall&
==== nautilus-scripts/Varios/Execute/gnome2-terminal-here ====
$ cat nautilus-scripts/Varios/Execute/gnome2-terminal-here
#!/bin/sh
# From Chris Picton
# Replaces a Script by Martin Enlund
# Modified to work with spaces in path by Christophe Combelles
# This script either opens in the current directory,
# or in the selected directory
base="`echo $NAUTILUS_SCRIPT_CURRENT_URI | cut -d'/' -f3- | sed 's/%20/ /g'`"
if [ -z "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" ]; then
dir="$base"
else
while [ ! -z "$1" -a ! -d "$base/$1" ]; do shift; done
dir="$base/$1"
fi
gnome-terminal --working-directory="$dir"
==== nautilus-scripts/Varios/Execute/Open_Terminal_Here ====
$ cat nautilus-scripts/Varios/Execute/Open_Terminal_Here
#!/usr/bin/perl -w
#
# Open terminal here
#
# Nautilus script that opens a gnome-terminal at the current location, if it's
# a valid one. This could be done in shell script, but I love Perl!.
#
# 20020930 -- Javier Donaire
# http://www.fraguel.org/~jyuyu/
# Licensed under the GPL v2+
#
# Modified by: Dexter Ang [thepoch@mydestiny.net]
# 2003-12-08: Modified for Gnome 2.4
# - Added checking if executed on Desktop "x-nautilus-desktop:///"
# so that it opens in /home/{user}/Desktop
use strict;
$_ = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'};
if ($_ and m#^file:///#) {
s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
s#^file://##;
exec "gnome-terminal --working-directory='$_'";
}
# Added 2003-12-08 Dexter Ang
if ($_ == "x-nautilus-desktop:///") {
$_ = $ENV{'HOME'};
$_ = $_.'/Desktop';
exec "gnome-terminal --working-directory='$_'";
}
==== nautilus-scripts/Varios/Execute/Play_in_XMMS ====
$ cat nautilus-scripts/Varios/Execute/Play_in_XMMS
#!/bin/sh
#
# Jani Soila 2001
# Public domain
# Gets arguments sorts them in alphabetical order
# and adds the list to xmms playlist.
# get arguments in array
i=0
for n ;
do
a[$((i++))]=$n ;
done
# sort array
for (( i=0; $i<(${#a[@]}-1); i++ )) ; do for (( j=i+1; $j<(${#a[@]}); j++ )) ; do if [[ ${a[$j]} < ${a[$i]} ]] ; then t=${a[$j]}; a[$j]=${a[$i]}; a[$i]=$t; fi done done # launch xmms with sorted list xmms -e "${a[@]}"
==== nautilus-scripts/Varios/Execute/root-nautilus-here ====
$ cat nautilus-scripts/Varios/Execute/root-nautilus-here
#!/bin/sh
# root-nautilus-here
# opens a root-enabled instance of a nautilus window in selected location
# requires sudo priviledges and gksudo, which may involve security risks.
#Install in your ~/Nautilus/scripts directory.
#
# Placed in the public domain by Shane T. Mueller 2001
# Fixes provided by Doug Nordwall
#
# 2004.04.18 -- keith@penguingurus.com - Added gksudo usage to provide popup
# password window if sudo has expired. Line only echos got
# root to std output. But gksudo updates your sudo access
# privs, so running nautilus with sudo will succeed
# without asking for a password.
foo=`gksudo -u root -k -m "enter your password for nautilus root access" /bin/echo "got r00t?"`
sudo nautilus --no-desktop $NAUTILUS_SCRIPT_CURRENT_URI
==== nautilus-scripts/Varios/Execute/root-terminal-here ====
$ cat nautilus-scripts/Varios/Execute/root-terminal-here
#!/bin/sh
#
#
#This script opens a root-based gnome-terminal in the directory you select.
# You need to have appropriate sudo priveleges.
#Install in your ~/Nautilus/scripts directory.
cd $NAUTILUS_SCRIPT_CURRENT_URI
sudo gnome-terminal
==== nautilus-scripts/Varios/Execute/run ====
$ cat nautilus-scripts/Varios/Execute/run
#!/bin/sh
appname=`gdialog --title "Execute Command" --inputbox "Enter name of application to execute\n on selected file(s)" 200 100 "" 2>&1`
for arg
do
exec "$appname" "$arg" &
done
==== nautilus-scripts/Varios/Execute/terminal-here ====
$ cat nautilus-scripts/Varios/Execute/terminal-here
#!/bin/sh
#
# This script opens a gnome-terminal in the directory you select.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Keith Conger
#
# Install in your ~/Nautilus/scripts directory.
# You need to be running Nautilus 1.0.3+ to use scripts.
cd $NAUTILUS_SCRIPT_CURRENT_URI
exec gnome-terminal
==== nautilus-scripts/Varios/Execute/xemacs ====
$ cat nautilus-scripts/Varios/Execute/xemacs
#!/bin/sh
#This script opens the selected file(s) in xemacs
xemacs $@
==== nautilus-scripts/Varios/Execute/xine ====
$ cat nautilus-scripts/Varios/Execute/xine
#!/bin/bash
#
# Nautilus script -> Laucher media file with Xine
#
# Owner : Largey Patrick Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Ver :1.01 Date 09.07.2002
# start xine without file://
#
# Ver :1.0 Date 04.02.2002
#
# Xine : http://xine.sourceforge.net/
#
video_file=""$PWD""/$1""
if [ -d "$1" ]
then
exit 0
else
xine "$video_file"&
fi
==== nautilus-scripts/Varios/Execute/XMMS ====
$ cat nautilus-scripts/Varios/Execute/XMMS
#!/usr/bin/perl
my @mp3list = @ARGV;
exec 'xmms', reverse (@mp3list);
==== nautilus-scripts/Varios/Execute/xsu-terminal-here ====
$ cat nautilus-scripts/Varios/Execute/xsu-terminal-here
#!/bin/sh
#
# Nautilus script -> Launch gnome-terminal as root using Xsu
#
# Author: Dan Whitfield
# danrw.geo@yahoo.com
# http://www.geocities.com/danrw.geo/
#
# License: free (public domain)
#
# Date: 20.02.2002
#
# Xsu: http://freshmeat.net/projects/xsu/ or http://xsu.freax.eu.org/
#
#
# This script uses Xsu (http://xsu.freax.eu.org/)to allow
# you to su to a specific username and password and then,
# open a gnome-terminal in the directory you select.
# The default user is root.
# Install this script in your ~/.gnome/nautilus-scripts or
# ~/.gnome/nautilus-scripts/Execute directory.
cd $NAUTILUS_SCRIPT_CURRENT_URI
xsu -c "gnome-terminal" -u "root" -m "To run the gnome-terminal with root access,^Enter the root password below." -i "/usr/share/pixmaps/gnome-terminal.png"
==== nautilus-scripts/Varios/FileInfo/filetype ====
$ cat nautilus-scripts/Varios/FileInfo/filetype
#!/bin/sh
# Copyright (C) Sept 13, 2001 Shane Mueller
# http://g-scripts.sourceforge.net
# Released into the public domain.
#
for arg
do
filetype=$(file "$arg")
gdialog --title "File-Type Determinator" --msgbox "File $filetype" 200 200
done
==== nautilus-scripts/Varios/FileInfo/FileUsedBy ====
$ cat nautilus-scripts/Varios/FileInfo/FileUsedBy
#!/bin/sh
a=$(lsof | grep "$@")
if [ $a == ""] ; then
gdialog --backtitle "Process File Usage" --msgbox "No Users" 25 20
else
gdialog --backtitle "Word Count Script" --msgbox "$a" 25 20fi
==== nautilus-scripts/Varios/FileInfo/ggrep ====
$ cat nautilus-scripts/Varios/FileInfo/ggrep
#!/usr/bin/perl -w
#
# ggrep -- A gtk-frontend for grep. You will need
# libgtk-perl to run this program
#
# Distributed under GNU GPL v2.0 or later
#
# Copyright (C) David Westlund
use Gtk;
use strict;
init Gtk;
set_locale Gtk;
my $true = 1;
my $false = 0;
# These will be used as gtk-widgets
my $window;
my $vbox;
my $hbox;
my $parameters_label;
my $parameters_entry;
my $regexp_label;
my $regexp_entry;
my $grep_button;
my $table;
my $scroll;
my $text;
my $close_button;
# The gtk-signals
my $signal;
$window = new Gtk::Window( 'toplevel' );
$signal = $window->signal_connect( 'delete_event', sub { Gtk->exit( 0 ); } );
$window->border_width( 15 );
$window->set_title( "gtk-grep" );
$vbox = new Gtk::VBox ( $false, 0 );
$window->add( $vbox );
$hbox = new Gtk::HBox ( $false, 0 );
$vbox->pack_start ($hbox, $false, $false, 0);
$hbox->show();
$parameters_label = new Gtk::Label ( "Parameters" );
$hbox->pack_start ($parameters_label, $false, $false, 0);
$parameters_label->show();
$parameters_entry = new Gtk::Entry ();
$hbox->pack_start ($parameters_entry, $false, $false, 0);
$parameters_entry->set_usize ( 200, undef );
$parameters_entry->show();
$regexp_label = new Gtk::Label ( "Search for: " );
$hbox->pack_start ($regexp_label, $false, $false, 0);
$regexp_label->show();
$regexp_entry = new Gtk::Entry ();
$hbox->pack_start ($regexp_entry, $false, $false, 0);
$regexp_entry->set_usize ( 300, undef );
$regexp_entry->show();
$grep_button = new Gtk::Button ( "Grep" );
$grep_button->signal_connect ('clicked', \&grep );
$hbox->pack_start ($grep_button, $false, $false, 0);
$grep_button->show();
$table = new Gtk::Table (2, 1, $false);
$table->set_usize ( 600, 500 );
$vbox->pack_start ($table, $false, $false, 0);
$table->show();
$text = new Gtk::Text ( undef, undef );
$text->set_editable ($false);
$table->attach( $text, 0, 1, 0, 1,
[ 'expand', 'fill' ],
[ 'expand', 'fill' ],
0, 0 );
$text->show;
$scroll = new Gtk::VScrollbar ( $text->vadj );
$table->attach( $scroll, 1, 2, 0, 1, 'fill',
[ 'expand', 'fill' ], 0, 0 );
$scroll->show;
$close_button = new Gtk::Button( "Close" );
$close_button->signal_connect( 'clicked', sub { Gtk->exit( 0 ); } );
$vbox->pack_start( $close_button, $false, $false, 0 );
$close_button->show();
$vbox->show();
$window->show();
main Gtk;
exit (0);
sub grep
{
my $length;
my $row;
my $parameters;
my $regexp;
my $files = " ";
$length = $text->get_length ();
$text->backward_delete ($length);
foreach (@ARGV) {
print ("$_");
$files = $files . $_ . " ";
}
$parameters = $parameters_entry->get_text();
$regexp = $regexp_entry->get_text();
open GREP, "grep $parameters '$regexp' $files 2>&1 |";
while ( $row =
$text->insert ( undef, undef,undef , $row );
}
close GREP;
}
==== nautilus-scripts/Varios/FileInfo/gtk2-du ====
$ cat nautilus-scripts/Varios/FileInfo/gtk2-du
#!/usr/bin/env python
#
# gtk2-du -- gtk2 frontend to du.
#
# Author: Krzysztof Luks
#
# Copyright (C) 2002 Krzysztof Luks
# Licence: GNU GPL v 2 or later.
#
# Dependency: python-gtk2
#
# This script is based on gtk-du. Gtk-du is copyright (C) David Westlund
#
#
# Version 0.1 -- 06-Nov-2002
# * initial pre-release
#
# Version 0.2 -- 07-Nov-2002
# * added scrollbar to text view
# * some layout adjustments
# * 'du' button replaced with 'execute' stock button
#
import gtk
import sys
import os
#set_locale Gtk;
def destroy(*args):
""" Callback function that is activated when the program is destoyed """
window.hide()
gtk.main_quit()
def du(*args):
buffer = text.get_buffer()
buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())
files = ""
for i in sys.argv[1:]:
files = files +"\"" + i + "\" "
parameters = parameters_entry.get_text()
out = os.popen("du " + parameters + " " + files, "r")
buffer.insert(buffer.get_start_iter(), out.read())
out.close()
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", destroy)
window.set_border_width(15)
window.set_title("gtk2-du")
window.set_default_size(400, 300)
vbox = gtk.VBox(gtk.FALSE, 0)
window.add(vbox)
hbox = gtk.HBox(gtk.FALSE, 0)
vbox.pack_start(hbox, gtk.FALSE, gtk.FALSE, 0)
parameters_label = gtk.Label("Parameters: ")
hbox.pack_start(parameters_label, gtk.FALSE, gtk.FALSE, 0)
parameters_label.show()
parameters_entry = gtk.Entry()
hbox.pack_start(parameters_entry, gtk.TRUE, gtk.TRUE, 10)
parameters_entry.set_text("-chs")
du_button = gtk.Button(stock='gtk-execute')
du_button.connect('clicked', du)
hbox.pack_start(du_button, gtk.TRUE, gtk.TRUE, 0)
scroll_win = gtk.ScrolledWindow()
scroll_win.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
vbox.pack_start(scroll_win, gtk.TRUE, gtk.TRUE, 0)
text = gtk.TextView()
text.set_editable(gtk.FALSE)
scroll_win.add(text)
close_button = gtk.Button(label = "Close")
close_button.connect('clicked', destroy)
vbox.pack_start(close_button, gtk.FALSE, gtk.FALSE, 0)
du()
window.show_all()
gtk.main()
==== nautilus-scripts/Varios/FileInfo/gtk2-grep ====
$ cat nautilus-scripts/Varios/FileInfo/gtk2-grep
#!/usr/bin/env python2.2
#
# gtk2-grep -- gtk2 frontend to grep.
#
# Copyright (C) 2003 David Westlund
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Dependency: python-gtk2
#
# This script is based on gtk2-du. Gtk2-du is copyright (C) Krzysztof Luks
import pygtk
pygtk.require('2.0')
import gtk
import sys
import os
#set_locale Gtk;
def destroy(*args):
""" Callback function that is activated when the program is destoyed """
window.hide()
gtk.main_quit()
def grep(*args):
buffer = text.get_buffer()
buffer.delete(buffer.get_start_iter(), buffer.get_end_iter())
files = os.environ.get('NAUTILUS_SCRIPT_SELECTED_FILE_PATHS')
files = files.split("\n")
files_string = ""
for i in files[0:]:
files_string = files_string +"\"" + i + "\" "
search = grep_entry.get_text()
parameters = parameters_entry.get_text()
out = os.popen("grep " + parameters + " \"" + search + "\" " + files_string, "r")
buffer.insert(buffer.get_start_iter(), out.read())
out.close()
if buffer.get_char_count() == 0:
buffer.insert(buffer.get_start_iter(), "No match found")
def check_enter(widget, key):
if key.keyval == 65293:
grep()
def check_escape(widget, key):
if key.keyval == 65307:
destroy()
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", destroy)
window.connect("key_press_event", check_escape)
window.set_border_width(12)
window.set_title("Search in files")
window.set_default_size(400, 300)
vbox = gtk.VBox(gtk.FALSE, 12)
window.add(vbox)
table = gtk.Table(2, 3, gtk.FALSE)
vbox.pack_start(table, gtk.FALSE, gtk.FALSE, 0)
table.show()
parameters_label = gtk.Label("Parameters for grep: ")
table.attach(parameters_label, 0, 1, 0, 1, gtk.FILL, gtk.FILL, 3, 3)
parameters_label.show()
parameters_entry = gtk.Entry()
parameters_entry.connect("key_press_event", check_enter)
table.attach(parameters_entry, 1, 3, 0, 1, gtk.FILL, gtk.FILL, 3, 3)
parameters_entry.show()
alignment = gtk.Alignment(0, 0, 0, 1)
grep_label = gtk.Label("Search after: ")
alignment.add(grep_label)
table.attach(alignment, 0, 1, 1, 2, gtk.FILL, gtk.FILL, 3, 3)
grep_label.show()
grep_entry = gtk.Entry()
grep_entry.connect("key_press_event", check_enter)
table.attach(grep_entry, 1, 2, 1, 2, gtk.FILL, gtk.FILL, 3, 3)
grep_entry.grab_focus()
grep_entry.show()
grep_button = gtk.Button(stock='gtk-find')
grep_button.connect('clicked', grep)
table.attach(grep_button, 2, 3, 1, 2, gtk.FILL, gtk.FILL, 3, 3)
grep_button.show()
scroll_win = gtk.ScrolledWindow()
scroll_win.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
vbox.pack_start(scroll_win, gtk.TRUE, gtk.TRUE, 0)
text = gtk.TextView()
text.set_editable(gtk.FALSE)
scroll_win.add(text)
button_box = gtk.HButtonBox()
button_box.set_layout(gtk.BUTTONBOX_END)
button_box.show()
vbox.pack_start(button_box, gtk.FALSE, gtk.FALSE, 0)
close_button = gtk.Button(stock='gtk-close')
close_button.connect('clicked', destroy)
button_box.add(close_button)
window.show_all()
gtk.main()
==== nautilus-scripts/Varios/FileInfo/gtk-du ====
$ cat nautilus-scripts/Varios/FileInfo/gtk-du
#!/usr/bin/perl -w
#
# gtk-du -- gtk frontend to du. You will need
# libgtk-perl to run the program.
#
# Distributed under the terms of GNU GPL v 2.0 or later
#
# Copyright (C) David Westlund
use Gtk;
#use strict;
init Gtk;
set_locale Gtk;
my $true = 1;
my $false = 0;
# These will be used as gtk-widgets
my $window;
my $vbox;
my $hbox;
my $parameters_label;
my $parameters_entry;
my $du_button;
my $table;
my $scroll;
my $text;
my $close_button;
# The gtk-signals
my $signal;
$window = new Gtk::Window( 'toplevel' );
$signal = $window->signal_connect( 'delete_event', sub { Gtk->exit( 0 ); } );
$window->border_width( 15 );
$window->set_title( "gtk-du" );
$vbox = new Gtk::VBox ( $false, 0 );
$window->add( $vbox );
$hbox = new Gtk::HBox ( $false, 0 );
$vbox->pack_start ($hbox, $false, $false, 0);
$hbox->show();
$parameters_label = new Gtk::Label ( "Parameters" );
$hbox->pack_start ($parameters_label, $false, $false, 0);
$parameters_label->show();
$parameters_entry = new Gtk::Entry ();
$hbox->pack_start ($parameters_entry, $false, $false, 0);
$parameters_entry->set_text ( "-chs" );
$parameters_entry->show();
$du_button = new Gtk::Button ( "du" );
$du_button->signal_connect ('clicked', \&du );
$hbox->pack_start ($du_button, $false, $false, 0);
$du_button->show();
$table = new Gtk::Table (2, 1, $false);
$table->set_usize ( 300, 200 );
$vbox->pack_start ($table, $false, $false, 0);
$table->show();
$text = new Gtk::Text ( undef, undef );
$text->set_editable ($false);
$table->attach( $text, 0, 1, 0, 1,
[ 'expand', 'fill' ],
[ 'expand', 'fill' ],
0, 0 );
$text->show;
$scroll = new Gtk::VScrollbar ( $text->vadj );
$table->attach( $scroll, 1, 2, 0, 1, 'fill',
[ 'expand', 'fill' ], 0, 0 );
$scroll->show;
$close_button = new Gtk::Button( "Close" );
$close_button->signal_connect( 'clicked', sub { Gtk->exit( 0 ); } );
$vbox->pack_start( $close_button, $false, $false, 0 );
$close_button->show();
$vbox->show();
$window->show();
du ();
main Gtk;
exit (0);
sub du
{
my $length;
my $row;
my $parameters;
my $files = " ";
$length = $text->get_length ();
$text->backward_delete ($length);
foreach (@ARGV) {
$files = $files . "\"$_\"" . " ";
}
$parameters = $parameters_entry->get_text();
open DU, "du $parameters $files 2>&1 |";
while ( $row =
$text->insert ( undef, undef,undef , $row );
}
close DU;
}
==== nautilus-scripts/Varios/FileInfo/mimetype ====
$ cat nautilus-scripts/Varios/FileInfo/mimetype
#!/bin/sh
# Copyright (C) Sept 13, 2001 Shane Mueller
# http://g-scripts.sourceforge.net
# Released into the public domain.
#
for arg
do
filetype=$(file -i "$arg")
gdialog --title "File-Type Determinator" --msgbox "File $filetype" 200 200
done
==== nautilus-scripts/Varios/FileInfo/Search_Here ====
$ cat nautilus-scripts/Varios/FileInfo/Search_Here
#!/bin/sh
# From Johnathan Bailes
# This script opens a gnome-search-tool in the directory you select.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Install in your ~/Nautilus/scripts directory.
# You need to be running Nautilus 1.0.3+ to use scripts.
cd $NAUTILUS_SCRIPT_CURRENT_URI
exec gnome-search-tool
==== nautilus-scripts/Varios/FileInfo/Show_MD5_Sum ====
$ cat nautilus-scripts/Varios/FileInfo/Show_MD5_Sum
#!/usr/bin/perl
###############################################################################
# Display the MD5 sums of the selected files
###############################################################################
#
# AUTHOR: Brian Connelly
# DESCRIPTION: This script displays the names and MD5 sums of the selected
# files
#
# REQUIREMENTS: Nautilus file manager
# gdialog, which is included in the gnome-utils package
# Perl
#
# INSTALLATION: GNOME 1.4.x: copy this script to the ~/Nautilus/scripts
# directory
# GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory
#
# USAGE: Select the files that you would like to display in Nautilus,
# right click, go to Scripts, and then select this script.
# A dialog window will then appear with the results for the
# selected files.
#
# VERSION INFO:
# 0.1 (20021009) - Initial public release
#
# COPYRIGHT: Copyright (C) 2002 Brian Connelly
#
# LICENSE: GNU GPL
#
###############################################################################
$script_title="MD5 Sum";
$temp_file = "/tmp/md5" . "-" . `date +'%s'`;
if(!@ARGV)
{
system("gdialog --title \"$SCRIPT_TITLE Error\" --msgbox \"No files have been selected\" 400 400 2>&1");
exit;
}
$num_files = @ARGV;
if($num_files < 30)
{
$num_rows = $num_files * 5;
}
elsif($num_files < 100)
{
$num_rows = $num_files
}
else
{
# just to make sure that the output window can't be too large
$num_rows = 80;
}
foreach $file (@ARGV)
{
if(-d $file)
{
system("echo \"Cannot calculate MD5 sum for directory '$file'\" 2>&1 >> $temp_file");
}
else
{
system("md5sum \"$file\" 2>&1 >> $temp_file");
}
}
chomp($temp_file);
system("gdialog --title \"$script_title Results\" --textbox $temp_file $num_rows 80 2>&1");
system("rm $temp_file");
==== nautilus-scripts/Varios/FileInfo/Show_Parameters ====
$ cat nautilus-scripts/Varios/FileInfo/Show_Parameters
#!/bin/sh
#
# Nautilus Script:
# Show the parameters passed by nautilus.
#
# Owner:
# Barak Korren
# ifireball@yahoo.com
#
# Licence: GNU GPL
# Copyright (C) Barak Korren
#
# Dependency:
# xmessage
#
# Change log:
# Mon, Apr 05, 2004 - Created.
#
# Known Issues:
# I'd like to use zentity instead of xmessage, but it doesn't currently
# support showing text from the standard input, too bad gless doesn't seem
# to be shipped with gnome-utils anymore, maybe one can use the builtin
# Nautilus text viewer?
#
(
echo "AGRS"
for arg in "$@"; do
echo "\"$arg\""
done
echo NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS"
echo NAUTILUS_SCRIPT_SELECTED_URIS
echo -e "$NAUTILUS_SCRIPT_SELECTED_URIS"
echo NAUTILUS_SCRIPT_CURRENT_URI
echo -e "$NAUTILUS_SCRIPT_CURRENT_URI"
echo NAUTILUS_SCRIPT_WINDOW_GEOMETRY
echo -e "$NAUTILUS_SCRIPT_WINDOW_GEOMETRY"
) | xmessage -file -
==== nautilus-scripts/Varios/FileInfo/wordcount ====
$ cat nautilus-scripts/Varios/FileInfo/wordcount
#!/bin/sh
a=$(wc -w "$@")
gdialog --backtitle "Word Count Script" --msgbox "Words: $a" 25 20
==== nautilus-scripts/Varios/FileProcessing/concatenate ====
$ cat nautilus-scripts/Varios/FileProcessing/concatenate
#!/bin/bash
# concatenates selected files in one file and moves the old ones to Trash
# to be used with files generated by 'split' GNU/Linux utility
# Marius Andreiana
# Licence: GPL
#
# TODO
# how to do it without temp file 'nautilus_script_files' ?
# force nautilus refresh after exec
#
concat_file_name=$( echo $1 | sed s/'..$'/""/g )
#cd $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
for arg
do
echo "$arg" >> nautilus_script_files
done
cat $( cat nautilus_script_files | sort ) > $concat_file_name
rm -f nautilus_script_files
for arg
do
mv "$arg" ~/.Trash
done
==== nautilus-scripts/Varios/FileProcessing/dos2unix ====
$ cat nautilus-scripts/Varios/FileProcessing/dos2unix
#!/bin/sh
#
# This script removes ^M carriage return characters from dos text files for proper unix formatting
# Placed in the public domain 2/2002 by Shane T. Mueller
for arg
do
uname=`date +/tmp/$arg-%m%d%Y.%H%M%S`
## uname should really be checked to see if it exists, and regenerated
## otherwise
tr -d '\015' < "$arg" > "$uname"
mv "$uname" "./$arg"
done
==== nautilus-scripts/Varios/FileProcessing/doublespace ====
$ cat nautilus-scripts/Varios/FileProcessing/doublespace
#!/bin/sh
#doublespace: Double-spaces selected file(s)
#requires unix sed
for arg
do
(sed G "$arg") > ds-"$arg"
done
==== nautilus-scripts/Varios/FileProcessing/latex ====
$ cat nautilus-scripts/Varios/FileProcessing/latex
#!/bin/bash
#
# LaTeX/TeX script for nautilus
#
# Copyright GPL
#
gdialog --msgbox `echo $*` 20 30
for file in "$*"
do
# Make sure that it is a TeX / LaTeX file
file_type=`file "$file"`
case "${file_type/*TeX*/TeX}" in
TeX)
output_type=`gdialog --title "(La)TeX script)" --radiolist "What form of output do you want" 200 400 3 '1' PDF on '2' PS off '3' DVI off '4' HTML off 2>&1`
echo .latex_$$.log
case $output_type in
1)
echo q | pdflatex $file >> .latex_$$.log
rm -f ${file/%tex/aux} ${file/%tex/log}
;;
2)
echo q | latex $file >> .latex_$$.log
dvips ${file/%tex/dvi} >> .latex_$$.log
rm -f ${file/%tex/aux} ${file/%tex/log} ${file/%tex/dvi}
;;
3)
echo q | latex $file >> .latex_$$.log
rm -f ${file/%tex/aux} ${file/%tex/log}
;;
4)
echo q | latex2html $file >> .latex_$$.log
;;
*)
exit 0;
esac
gdialog --title "(La)TeX script)" --textbox .latex_$$.log 25 80
rm -f .latex_$$.log
;;
*)
gdialog --title "(La)TeX script)" --msgbox "Could not process $file - Unsupported type: $file_type" 200 400
;;
esac
done
==== nautilus-scripts/Varios/FileProcessing/latex2ps ====
$ cat nautilus-scripts/Varios/FileProcessing/latex2ps
# Bubba's improved nautilus latex2ps script
# V3 - bibtex and re-run for references
# phurd@ualberta.ca
cd $NAUTILUS_SCRIPT_CURRENT_URI
BASENAME=`echo $1 | cut -d"." -f1`
TMPFILE=`echo ~/.latex2ps.$RANDOM.temp`
# something is stripping off a backslashes throughout when posting to
# the g-scripts-devel list... should be two before nonstopmode and two
# before input
latex \\nonstopmode\\input $@ > $TMPFILE
BIBTEX_PRESENT=`grep -c "bibliographystyle" $@`
if [ $BIBTEX_PRESENT ]
then
bibtex $BASENAME >> $TMPFILE
latex \\nonstopmode\\input $@ >> $TMPFILE
fi
UNDEFINED_REFERENCE=`grep -c "undefined references" $TMPFILE`
UNDEFINED_CITATION=`grep -c "undefined citations" $TMPFILE`
UNDEFINED=$UNDEFINED_REFERENCE+$UNDEFINED_CITATION
if [ $UNDEFINED ]
then
latex \\nonstopmode\\input $@ >> $TMPFILE
fi
BASENAME=`echo $1 | cut -d"." -f1`
dvips $BASENAME -o $BASENAME.ps
gless $TMPFILE
rm $TMPFILE
==== nautilus-scripts/Varios/FileProcessing/mail_file ====
$ cat nautilus-scripts/Varios/FileProcessing/mail_file
#!/bin/bash
#
# TODO: Fix the problem with space in the name in a better way
# (which may be any other possible way at all...)
#
case $LANG in
sv* )
EMAILADDR='Epost-addresser'
WRITEMESSAGE='Skriv meddelande'
SUBMES='Skriv meddelande (\C4mne:Meddelande)'
SEND='Skicka';;
* )
EMAILADDR='Email addresses'
WRITEMESSAGE='Write message'
SUBMES='Write message (subject:message)'
SEND='Send';;
esac
EMAILS="`gdialog --title "$EMAILADDR" --inputbox "$EMAILADDR" 200 100 2>&1`"
echo $EMAILS
MESSAGE="`gdialog --title "$SUBMES" --inputbox "$WRITEMESSAGE" 200 100 2>&1`"
echo $SUBMES
FILES=""
while [ $# -gt 0 ]; do
FILE=$PWD/$1
FILE=`echo $FILE | sed 's/ /\?/g'`
FILES="$FILES $FILE"
shift
done
SUBJECT=`echo $MESSAGE | sed 's/:.*//'`
MESSAGE=`echo $MESSAGE | sed 's/.*://'`
echo "$MESSAGE" | uuenview -a $FILES -s "$SUBJECT" -b -m "$EMAILS"
==== nautilus-scripts/Varios/FileProcessing/mail_file2 ====
$ cat nautilus-scripts/Varios/FileProcessing/mail_file2
#!/bin/bash
# FILE: mail_file --
# AUTHOR: W. Michael Petullo
# DATE: 31 May 2001
#
# Copyright (C) 2001 W. Michael Petullo
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# ============================= shrink_image () ===============================
shrink_image()
{
cp $1 $tmpdir
tmpfile=${tmpdir}/`basename $1`
mogrify -geometry '640x480>' $tmpfile
echo ${tmpfile}
}
# ============================= main () =======================================
tmpdir=`mktemp -d /tmp/mail-image-XXXXXX`
trap 'rm -rf $tmpdir' SIGHUP SIGINT SIGTERM EXIT
if [ -z $MAILER ]; then
MAILER=balsa
MAILER_NEEDS_GNOME_TERMINAL=false
fi
for i in $*; do
MAGIC=`file $i`
echo $MAGIC
case `echo $MAGIC | tr 'A-Z' 'a-z'` in
*jpeg* )
attachments="${attachments} -a `shrink_image $i`" ;;
*gif* )
attachments="${attachments} -a `shrink_image $i`" ;;
*png* )
attachments="${attachments} -a `shrink_image $i`" ;;
*tiff* )
attachments="${attachments} -a `shrink_image $i`" ;;
* )
attachments="${attachments} -a $i"
esac
done
if [ x$MAILER_NEEDS_GNOME_TERMINAL = xtrue ]; then
gnome-terminal -x $MAILER $attachments
else
$MAILER $attachments
fi
==== nautilus-scripts/Varios/FileProcessing/Mail_In_Evolution ====
$ cat nautilus-scripts/Varios/FileProcessing/Mail_In_Evolution
#!/usr/bin/perl -w
# By John Russell
# This script sends the selected file(s) with evolution.
use strict;
my $MAILTO_URL="mailto:?";
my @files = split("\n", $ENV{NAUTILUS_SCRIPT_SELECTED_FILE_PATHS});
my $count = 0;
foreach my $file (@files)
{
if ( ! -f $file && ! -l $file )
{
my @dialog = ("gdialog","--title","Error","--msgbox", "\nError: Can not send $file. \n\n Only regular files can be mailed. ","200", "300");
system (@dialog);
}
else
{
$MAILTO_URL = $MAILTO_URL . "attach=" . $file . "&";
shift;
$count += 1;
}
}
if ($count > 0)
{
my @command = ("evolution", $MAILTO_URL);
system(@command);
}
==== nautilus-scripts/Varios/FileProcessing/maker ====
$ cat nautilus-scripts/Varios/FileProcessing/maker
#!/bin/sh
case $LANG in
fr* )
title="Decompacteur"
beuh="format inconnu"
ncompr="ne peut \EAtre d\E9compress\E9"
compr="est d\E9compress\E9" ;;
sv* )
title="Packa upp"
beuh="Ok\E4nt format"
ncompr="kunde inte packas upp korrekt"
compr="\E4r uppackad" ;;
* )
title="Uncompress"
beuh="Unknown format"
ncompr="could not be decompressed"
compr="is decompressed" ;;
esac
decompressed=""
errors=""
while [ $# -gt 0 ]
do
error=0
#
# tar.gz format
#
if
ext=`echo "$1" | grep [.]tar.gz$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
tar -xzf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
#
# tgz format
#
elif
ext=`echo "$1" | grep [.]tgz$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
tar -xzf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
#
# tar format
#
elif
ext=`echo "$1" | grep [.]tar$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
tar -xf "$1" || error=1
dir=`ls | cut -f 2 -d 'r'`
#
# gz format
#
elif
ext=`echo "$1" | grep [.]gz$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
gunzip -N "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
#
# tar.bz2 format
#
elif
ext=`echo "$1" | grep [.]tar.bz2$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
tar -jxf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
#
# bz2 format
#
elif
ext=`echo "$1" | grep [.]bz2$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
bunzip2 -k "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
#
# zip format
#
elif
ext=`echo "$1" | grep [.]zip$ 2>&1`
[ "$ext" != "" ]
then
unzip "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
#
# rar format
#
elif
ext=`echo "$1" | grep [.]rar$ 2>&1`
[ "$ext" != "" ]
then
mkdir tmp
mv "$1" tmp
cd tmp
unrar x -kb -o+ "$1" || error=1
dir=`ls | cut -f 2 -d 'r'`
#
# ??? format
#
else
gdialog --title "$title" --msgbox "$1 $beuh" 200 100
error=-1;
fi
if [ $error != -1 ]; then
if [ $error = 0 ]; then
decompressed="$decompressed $1"
else
errors="$errors $1"
fi
fi
shift
done
if [ "$decompressed" != "" ]; then
gdialog --title "$title" --msgbox "$decompressed $compr" 200 100
fi
if [ "$errors" != "" ]; then
gdialog --title "$title" --msgbox "$errors $ncompr" 200 100
fi
cd $NAUTILUS_SCRIPT_CURRENT_URI
cd $dir
./configure --prefix=/usr
make
gdialog --title "Maker" --msgbox "Compiled and made" 200 100
==== nautilus-scripts/Varios/FileProcessing/new-text-document ====
$ cat nautilus-scripts/Varios/FileProcessing/new-text-document
#!/bin/sh
#
# Add a new text file in the current directory.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) 2003 Dexter Ang [thepoch@mydestiny.net
# based on work by Jeffrey Philips and Johnathan Bailes
# and a script I found on themedepot.org
# KNOWN BUGS:
# - Never tested with an invalid directory. Don't know how.
# - When you enter a blank filename, it generates a .txt hidden file.
# - There's probably more.
# 2003-12-08 Dexter Ang [thepoch@mydestiny.net]
# Modified for Nautilus 2.4
# -- now detects if executed on desktop "x-nautilus-desktop:///"
# so that it creates the file in /home/{user}/Desktop
# Remove comment to set Debug Mode. Displays crucial variable values
#DEBUG_MODE=1
# Remove comment to automatically generate filename. Set to 1 to ask for filename
#ASK_MODE=1
# Set the default extension of your preference here
EXTENSION="txt"
# Function for displaying variable values and anything else I want
debug() {
[ -n "$DEBUG_MODE" ] && gdialog --title "Debug Mode" --msgbox "$*" 200 100
}
# This gets the current directory. It is "space-space" as it replaces %20 with spaces
Current_Dir="`echo "$NAUTILUS_SCRIPT_CURRENT_URI" | sed -e 's/^file:\/\///' -e 's/%20/\ /g'`"
# Added 2003-12-08 Dexter Ang
if [ $Current_Dir == "x-nautilus-desktop:///" ]; then
Current_Dir=$HOME"/Desktop"
fi
debug "Current_Dir = $Current_Dir"
if [ $ASK_MODE == "1" ]; then
debug "In Ask Mode"
New_Document="`gdialog --title "New Filename" --inputbox "Enter a new filename" 200 100 2>&1`"
if [ $? -ne "0" ]; then
debug "Canceled"
exit 1
fi
else
debug "In Non-Ask Mode"
New_Document="New Text Document"
fi
debug "New_Document = $New_Document"
COUNT=1
# If file doens't exist, touch it
if ! [ -a "$Current_Dir/$New_Document.txt" ] ; then
touch "$Current_Dir/$New_Document.txt"
# else, go loop until you get a number that works!
else
while ! [ "$retry" ] ; do
let $((COUNT++))
if ! [ -a "$Current_Dir/$New_Document($COUNT).txt" ] ; then
touch "$Current_Dir/$New_Document($COUNT).txt"
retry=1
fi
done
fi
==== nautilus-scripts/Varios/FileProcessing/New_Text_Document ====
$ cat nautilus-scripts/Varios/FileProcessing/New_Text_Document
#!/bin/sh
#
# Add a new text file in the current directory.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) 2003 Dexter Ang [thepoch@mydestiny.net
# based on work by Jeffrey Philips and Johnathan Bailes
# and a script I found on themedepot.org
# KNOWN BUGS:
# - Never tested with an invalid directory. Don't know how.
# - When you enter a blank filename, it generates a .txt hidden file.
# - There's probably more.
#
# 2003-12-08 Dexter Ang [thepoch@mydestiny.net]
# Modified for Nautilus 2.4
# -- now detects if executed on desktop "x-nautilus-desktop:///"
# so that it creates the file in /home/{user}/Desktop
# Remove comment to set Debug Mode. Displays crucial variable values
#DEBUG_MODE=1
# Remove comment to automatically generate filename. Set to 1 to ask for filename
#ASK_MODE=1
# Set the default extension of your preference here
EXTENSION="txt"
# Function for displaying variable values and anything else I want
debug() {
[ -n "$DEBUG_MODE" ] && gdialog --title "Debug Mode" --msgbox "$*" 200 100
}
# This gets the current directory. It is "space-space" as it replaces %20 with spaces
Current_Dir="`echo "$NAUTILUS_SCRIPT_CURRENT_URI" | sed -e 's/^file:\/\///' -e 's/%20/\ /g'`"
# Added 2003-12-08 Dexter Ang
if [ $Current_Dir == "x-nautilus-desktop:///" ]; then
Current_Dir=$HOME"/Desktop"
fi
debug "Current_Dir = $Current_Dir"
if [ $ASK_MODE == "1" ]; then
debug "In Ask Mode"
New_Document="`gdialog --title "New Filename" --inputbox "Enter a new filename" 200 100 2>&1`"
if [ $? -ne "0" ]; then
debug "Canceled"
exit 1
fi
else
debug "In Non-Ask Mode"
New_Document="New Text Document"
fi
debug "New_Document = $New_Document"
COUNT=1
# If file doens't exist, touch it
if ! [ -a "$Current_Dir/$New_Document.txt" ] ; then
touch "$Current_Dir/$New_Document.txt"
# else, go loop until you get a number that works!
else
while ! [ "$retry" ] ; do
let $((COUNT++))
if ! [ -a "$Current_Dir/$New_Document($COUNT).txt" ] ; then
touch "$Current_Dir/$New_Document($COUNT).txt"
retry=1
fi
done
fi
==== nautilus-scripts/Varios/FileProcessing/pdf2ps ====
$ cat nautilus-scripts/Varios/FileProcessing/pdf2ps
#!/usr/bin/python
# PDF to Postscript - converts a PDF file to Postcript
# by invoking pdf2ps
# Christopher Culver
from os import execvp
from sys import argv
pdf_file = []
pdf_file.append(argv[1])
execvp('pdf2ps', ['pdf2ps']+pdf_file)
==== nautilus-scripts/Varios/FileProcessing/pixdir2html.pl ====
$ cat nautilus-scripts/Varios/FileProcessing/pixdir2html.pl # body=
# table= # standard modules use Getopt::Long; use File::Copy; # for progressbar # non-standard modules: # borrowed ideas from UDPM.pm for the progressbar. # end of loading needed modules my $VERSION="1.4"; $|++; # disable buffer (autoflush) my $USAGE = " force - creates a .pixdir2htmlrc in every subdir overriding e.g. is the same as: "; # Get Nautilus current working directory, if under Natilus: my $nautilus_root = ""; if ( exists $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'} my $ROOT_DIRECTORY= ( -d $nautilus_root ) ? $nautilus_root : "."; # list directories that should be skipped here # dont worry if you don't have a log rotation facility... ###Nothing below this line should need to be configured.### my @pixdir = (); # for menu #my $tty = qx/tty/; # this returns text from system("tty") # xdialog is a better implementation than gdialog # make sure DIA is set or exit abnormally # get options die $USAGE if $HELP; my $FILE_NAME="index"; my $LOGFILE = new FileHandle; my $THUMBNAILSDIR="$ROOT_DIRECTORY/$THUMBNAIL"; warn << "__EOF__";
Perl pixdir2html v$VERSION
(Luis Mondesi main(); #-------------------------------------------------# $LOGFILE->open("> $LOG"); # for now --clear is the same for all dialogs: $GAUGE->open("| $DIA $ARGS --backtitle 'Picture Directory to HTML' # which progressbar are we using? # are we creating a menu file only? print $LOGFILE "= Start directory $ROOT_DIRECTORY \n"; if ( ! -f "$ROOT_DIRECTORY/$CONFIG_FILE" ) # get menu string # make all thumbnails and indices if ( $THUMBSONLY > 0 ) { # make all supporting HTML files # close GAUGE # close log if ( -x $SAVELOG ) { return 0; sub init_config { # some defaults: "; "; if ( -f "$ROOT/$CONFIG_FILE" ) #construct a header if it doesn't yet exist: ".$config_tmp{$ROOT}{"stylesheet"}." #construct a footer if it doesn't yet exist: # ext can be passed in a .pixdir2htmlrc file # save hash #return %config_tmp; sub mkindex { # takes a two-dimensional array in the form: # TODO see why this doesn't work as expected } elsif ( ! -f "$this_base/.nopixdir2htmlrc" ) { # "serialization" # yet another sort... # FILE_NAME is a global # start HTML \n"); \n"); \n"); \n"); \n"); sub mkthumb { print $LOGFILE ("= Making thumbnails in $ROOT \n"); # remove duplicates: # parse array of images # TODO make this into a function and re-use it... # progressbar stuff print $LOGFILE ("= $TOTAL pictures \n"); # this is just to clear up all if ( ! -f "$BASE/$CONFIG_FILE" && ! -f "$BASE/.nopixdir2htmlrc" # read specific config file for this directory # update flag # construct PATH for thumbnail directory #print STDOUT $HTMLSDIR."\n"; if ( !-f "$THUMBNAILSDIR/".$THUMB_PREFIX.$pix_name ){ # save pixname for the index.html file if ( $NOINDEX == 0 ) { } # end mkthumb sub thumb_html_files { my @ary = (); if ( # remove duplicates: # parse array of files, get images only # yet yet another sort!!! goodness # progressbar stuff # start HTML \n if ( -f $ls[$i+1] ) { print FILE (" \n"); \n"); # update progressbar sub menu_file { init_config($ROOT_DIRECTORY); my $MENU_STR = ""; # return this instead of making file my @ary = do_dir_ary("$ROOT_DIRECTORY"); # remove duplicates: # for e/a directory here if ( $ls[$x] = # sort menus alphabetically (dictionary order): if ( $MENUONLY > 0 ) { # menus are now part of the index.EXT... # generate menu if ( $total_links > 1 ) print FILE ($tmp_tr."\n"); } else { \n"); if ( $ls[$i] ne "" ) { # remove CUT_DIRS number of directories from ts my $tmp_ts = str_truncate($ts); $IMG = (-f "$ts/.new") ? " \n"); \n"; # remove CUT_DIRS number of directories from ts my $tmp_ts = str_truncate($ts); \n"; \n"); \n"; # ---- HELPER functions ----- # sub str_truncate sub progressbar sub progressbar_msg chomp($MESSAGE); sub do_dir_ary { my $ROOT = shift; sub process_dir { sub do_file_ary { sub process_file { sub cut_dirs { for ( my $i = 0; $i <= $#tmp_path; $i++ )
{
if ( $i >= $cut ) # to be safe, display the last name
#!/usr/bin/perl
# $Revision: 1.1 $
# Luis Mondesi
#
# USAGE:
# SEE HELP:
# pixdir2html.pl --help
#
# For the Impatient:
# pixdir2html.pl . # passes current directory to script as root
# # this is assumed by default
#
# pixdir2html.pl -f # force copies the root/.pixdir2htmlrc
# # to all other directories within this tree
# pixdir2html.pl --menuonly # generates a menu.$EXT file only
# # see "menuheader_footer" var
# # in case you don't want headers/
# # footers in that file (as if
# # that file is a .php and will
# # be included in other files...
# # or if you don't want menus in the
# # html files created
# # set to 0: no menus whatsoever
#
# DESCRIPTION:
#
# Use this non-interactive script in Nautilus to create HTML files
# with their proper thumbnails for pictures (.jpeg, .gif or .png)
#
# Make this file executable and put it in:
# ~/.gnome/nautilus-scripts
# or
# ~/.gnome2/nautilus-scripts
#
# Then run it from from the File::Scripts::script_name menu in Nautilus
#
# You could customize each directory differently by having a
# file named .pixdir2htmlrc in the directory containing the
# pictues. This file has the form:
#
# uri=http://absolute.path.com/images # must be absolute. no trailing /
# header=
# percent=30% #size of the thumbnails for this folder
# title=
# meta=
# stylesheet=
# html_msg=
Free form using HTML tags
# p=
# td=
# tr=
# new=http://absolute.path.com/images/new.png # for dirs with .new files
# footer=A footer here
# # set this to 1 to avoid printing a header
# # or footer in the menu file menu.$EXT
# menuheader_footer=0
# ext=php
#
# These are the only tags that you can customize for now :-)
#
# If you don't create a file, a sample will be done for you
# at the root level of the directory from which you execute
# this script.
#
# REQUIRED: ImageMagick's Perl module and it's dependancies
#
# TODO:
#
# * read TODO scatter thru the script...
#
# * do html_msg per photo in a .pixdir2htmlrc file:
# pix_"filename" = message for this file
#
# * clean() function to cleanup all files created by this script
# HINT:
# find . -name "[$LOGFILE*|*.$EXT|$html_dir|$thumbnails_dir]" -exec rm
-fr {} \;
# * internationalization of strings
# * test in windows or other non-unix that run Perl
#
# BUGS:
# * config file should not contain double quotes (") without
# escaping them first (\")
#
# TIPS:
#
# Put a .nopixdir2htmlrc file in directories for which you do not want
# thumbnails and/or index.$EXT to be written
#
use strict;
use vars qw( $VERSION @INC );
use Config;
Getopt::Long::Configure('bundling');
use File::Find; # find();
use File::Basename; # basename();
use FileHandle;
eval "use Image::Magick";
if ($@)
{
print STDERR "\nERROR: Could not load the Image::Magick module.\n" .
" Please install this module before continuing\n".
" Use: perl -e shell -MCPAN to install it.\n".
" On Debian just: apt-get install perlmagic \n\n";
print STDERR "$@\n";
exit 1;
}
# TODO else use "convert" if found
# didn't use it because it's too bloated for what
# I needed, and it created an extra module that
# users would have to install... nice work though
#
#eval "use UDPM";
pixdir2html.pl [-n|--nomenu]
[-N|--noindex]
[-f|--force]
[-M|--menuonly]
[-E|--extension] (php)
[-t|--thumbsonly]
[-D|--directory] (.)
[-l|--menulinks]
[-c|--cut-dirs]
[-h|--help]
any file with that name
nomenu - do not create menu file after finishing creating thumbnails
noindex - do not create the index.EXT files after creating thumbnails
menuonly - only create a menu file and exit
menulinks- number of links to put in the Menu per row. Default is 10
cut-dirs - number of directories to cut from the Menu string. Default is 0
extension- use this extension instead of default (php)
directory- use this directory instead of default (current)
menu_td - How many cells in menu?
td - How many cells in e/a file
str_limit- What's the size of the longest string allowed in menus?
help - prints this help and exit\n
cd /path/to/picture_directory
pixdir2html --extension='html'
pixdir2html -E html
&& $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'} =~ m#^file:///#
)
{
($nautilus_root = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'} ) =~
s#%([0-9A-Fa-f]{2})#chr(hex($1))#ge;
($nautilus_root = $nautilus_root ) =~ s#^file://##g;
}
my $LOG="$ROOT_DIRECTORY/pixdir2html.log";
my $CONFIG_FILE=".pixdir2htmlrc";
my $THUMBNAIL="t"; # individual thumnails files will be placed here
my $HTMLDIR="h"; # individual HTML files
my $EXT="php"; # default extension for generated HTML files
my $THUMB_PREFIX = "t"; # no need to ever change this... this starts
# the name for all thumbnail images
# separated by |
my $EXCEPTION_LIST = "CVS|RCS";
# regex of files we want to include
my $EXT_INCL_EXPR = "\.(jpg|png|jpeg|gif)";
# How big are the thumbnails?
# This is the default, in case the config file
# doesn't exist or do not have this item in it
my $PERCENT="20%";
# How many TDs per table in e/a index.EXT?
my $TD=4;
# How many TDs per menu table?
my $menu_td=10;
# How big are strings in menus?
my $STR_LIMIT = 32;
# just leave it as is
my $SAVELOG = "/usr/bin/savelog";
#**************************************************************#
my @pixfile = (); # for thumbfiles/pictures
my %config = (); # hash of hashes to hold config per directories
my $total_directories=0;
my $total_links=0;
my $FORCE=0;
my $NOMENU=0;
my $MENUONLY=0;
my $THUMBSONLY=0;
my $CUT_DIRS=0;
my $NOINDEX=0;
my $HELP=0;
# progressbar stuff here:
# initialization:
my $GAUGE = new FileHandle;
my $MODE = "text";
my $DIA = "";
# thus, if we find that, we use that first
# else, we try an alternate name
# TODO make sure this works in different systems/shells
# Go thru the PATH variable and finding the binaries:
# (this might not work on some systems...)
my @xbinaries = ("Xdialog","xdialog","gdialog","kdialog");
my @binaries = ("dialog","whiptail","cdialog");
my $FOUND = 0; # flag
foreach my $path ( split(/:/,$ENV{"PATH"}) )
{
next if ( $FOUND == 1 );
if ( exists $ENV{"NAUTILUS_SCRIPT_CURRENT_URI"} )
{
$MODE = "x";
foreach my $binary ( @xbinaries ) {
next if ( $FOUND == 1 );
if ( -x "$path/$binary" ) {
$DIA = "$path/$binary";
# gets out of these loops
$FOUND = 1;
}
} # end foreach @xbinaries
} else {
$MODE = "text";
foreach my $binary ( @binaries ) {
next if ( $FOUND == 1 );
if ( -x "$path/$binary" ) {
$DIA = "$path/$binary";
$FOUND = 1;
}
} # end foreach @binaries
} # end if NAUTILUS_SCRIPT_CURRENT_URI
} # end foreach $PATH
if ( $MODE eq "x" ) {
if ( $DIA eq "" ) {
# error
print STDERR ("Graphical Dialog was not found.\n");
print STDERR ("Please install any of these programs:\n");
print STDERR join(" ",@xbinaries)."\n";
exit 1;
}
} elsif ( $MODE eq "text" )
{
if ( $DIA eq "" ) {
# error
print STDERR ("Console Dialog was not found.\n");
print STDERR ("Please install any of these programs:\n");
print STDERR join(" ",@binaries)."\n";
exit 1;
}
}
GetOptions(
# flags
'n|nomenu' => \$NOMENU,
'f|force' => \$FORCE,
'h|help' => \$HELP,
'M|menuonly' => \$MENUONLY,
't|thumbsonly' => \$THUMBSONLY,
'N|noindex' => \$NOINDEX,
'l|menulinks=i' => \$menu_td,
# strings
'E|extension=s' => \$EXT,
'D|directory=s' => \$ROOT_DIRECTORY,
# numbers
'menu_td=i' => \$menu_td,
'td=i' => \$TD,
'str_limit=i' => \$STR_LIMIT,
'c|cut-dirs=i' => \$CUT_DIRS
);
my $MENU_NAME="menu";
my $menu_str="";
my $HTMLSDIR="$ROOT_DIRECTORY/$HTMLDIR";
(running with Perl $] on $Config{'archname'}) \n \n
__EOF__
# FUNCTIONS #
#-------------------------------------------------#
sub main {
$LOGFILE->autoflush(1);
# ( $MODE eq "x" ) ? " --clear ":
my $ARGS = " --clear ";
--title 'Picture Progress' --gauge 'Thumbnails Creation' 8 70 0 2>&1");
$GAUGE->autoflush(1);
print $LOGFILE ("Mode $MODE\n");
if ( $MENUONLY > 0 ) {
print $LOGFILE ("= Creating menu file\n");
menu_file();
return 0;
}
{
print $LOGFILE ( "Missing main $CONFIG_FILE. Creating one for you
\n");
init_config($ROOT_DIRECTORY,"true");
}
# TODO
# this will generate a list of all
# directories that don't have a .nopixdir2htmlrc
# file in them and assume that a index.$EXT file
# will be created later during this script
# execution. I don't like this assumption
# and will fix this later...
# For now it just works. This way we get a uniform
# Menu string for all index files.
unless ( $NOMENU == 1 ) {
print $LOGFILE ("= Creating menu string\n");
$menu_str = menu_file();
}
mkthumb($ROOT_DIRECTORY,$menu_str);
# this is a quick "dirty" way of getting only
# thumbnails and their respetive index.html files
return 0;
}
thumb_html_files($ROOT_DIRECTORY);
#print $GAUGE "\x04";
#$GAUGE->close();
eof($GAUGE);
undef($GAUGE); # this also closes the gauge... but...
print $LOGFILE ("$total_directories directories.\n\n");
$LOGFILE->close();
system("$SAVELOG $LOG > /dev/null 2>&1");
}
} # endmain
# Takes one argument:
# ROOT = directory from which we will take the config file
my %config_tmp = ();
my $ROOT = shift;
my $create_config = shift;
my $line="";
#
# it's very important to set this to a
# full URI:
# file:///path/to/root/directory
# http://www.server.tld/path/to/root/directory
# where "root directory" is the main dir
# where all other directories reside (and not
# the / root filesystem of UNIX/Linux/...).
# For now, ".." do the trick for a simple
# tree of directories:
# ROOT/
# ROOT/dir_a
# ROOT/dir_b
# ROOT/dir_c
#
# and not
# ROOT/
# ROOT/dir_a/dir_a1/dir_a2
# ROOT/dir_b ...
# for which case you will need a full path
$config_tmp{$ROOT}{"uri"}="..";
$config_tmp{$ROOT}{"percent"}=$PERCENT;
$config_tmp{$ROOT}{"title"}="Images";
$config_tmp{$ROOT}{"meta"}="";
$config_tmp{$ROOT}{"stylesheet"}="
";
$config_tmp{$ROOT}{"html_msg"}="
Free form HTML
$config_tmp{$ROOT}{"body"}="
$config_tmp{$ROOT}{"p"}="
$config_tmp{$ROOT}{"table"}="
";
$config_tmp{$ROOT}{"td"}="
";
$config_tmp{$ROOT}{"tr"}="
";
# when header is set, title, meta, stylesheet, etc...
# are discarded. So do a complete set
# such as
# and close with "footer"
$config_tmp{$ROOT}{"header"}="";
$config_tmp{$ROOT}{"footer"}="";
$config_tmp{$ROOT}{"menuheader_footer"}=0;
$config_tmp{$ROOT}{"ext"}=$EXT;
{
open(CONFIG, "<$ROOT/$CONFIG_FILE");
# suppress warnings for now...
no warnings;
while ( defined($line =
next if /^\s*#/;
chomp $line;
# attempts to be forgiven about backslashes
# to break lines that continues over
# multiple lines
if ($line =~ s/\\$//) {
$line .=
redo unless eof(CONFIG);
}
$config_tmp{$ROOT}{"$1"} = $2 if ( $line =~ m,^\s*([^=]+)=(.+),
);
}
close(CONFIG);
} else {
warn << "__EOF__";
Could not find $ROOT/$CONFIG_FILE
__EOF__
if ( $create_config =~ /true/ )
{
if (open(CONFIG, ">$ROOT/$CONFIG_FILE")) {
foreach my $key ( keys %config_tmp ) {
print CONFIG "$key=" . $config_tmp{"$key"}."\n";
}
} else {
print STDERR "Could not write $ROOT/$CONFIG_FILE. Check
permissions?";
}
}
}
if ( $config_tmp{$ROOT}{"header"} =~ /^\s+$/ )
{
print $LOGFILE (": Blank header. Generating my own [$ROOT] ... \n");
$config_tmp{$ROOT}{"header"}="
".$config_tmp{$ROOT}{"meta"}."
\n".
$config_tmp{$ROOT}{"body"}."
\n
$config_tmp{$ROOT}{"html_msg"}."\n";
}
if ( $config_tmp{$ROOT}{"footer"} eq "" )
{
print $LOGFILE (": Blank footer. Generating my own [$ROOT] ... \n");
$config_tmp{$ROOT}{"footer"}="
}
# like: ext=html or ext=php ...
if (
! exists $config_tmp{$ROOT}{"ext"} ||
$config_tmp{$ROOT}{"ext"} eq ""
) {
# default to HTML extension
$config_tmp{$ROOT}{"ext"}="html";
}
%config = %config_tmp;
} # end init_config
# mkindex is a private function called by
# mkthumb()
# $name{base}->[0] = 'path/file'
# and does a index file for e/a 'base' of
# all files referenced
my $hashref = $_[0]; # saves the name of the var passed
# e/a key holds a full array of files
my $MENU_STR = $_[1]; # a str to be included in e/a file
my $i = 0;
my (
$this_file,
$this_base
) = ""; # holds keys for hash
my @files = ();
# there is no need to sort this now... more testing needed
foreach $this_base ( sort keys %$hashref ) {
my ($my_bgcolor,$file_name) = "";
$i = 0;
# read specific config file for this directory
if ( -f "$this_base/$CONFIG_FILE" && ! -f
"$this_base/.nopixdir2htmlrc" ) {
if ( ! exists $config{$this_base} )
{
init_config($this_base);
} else {
# print only if debugging...
print $LOGFILE ": Exists in DB: $this_base \n";
} # end if/else not exists
# oops, missing config... getting base file
if (
copy("$ROOT_DIRECTORY/$CONFIG_FILE",
"$this_base/$CONFIG_FILE")
) {
print $LOGFILE (": Copied ".
" $ROOT_DIRECTORY/$CONFIG_FILE ".
"==> $this_base/$CONFIG_FILE \n");
}
# now read the config file
# and init a %config{this_base} hash for us
init_config($this_base);
}
my @files = @{$$hashref{$this_base}};
# sort menus alphabetically (dictionary order):
# print STDERR join(' ', @ls), "\n";
my $da;
my $db;
@files = sort {
($da = lc $a) =~ s/[\W_]+//g;
($db = lc $b) =~ s/[\W_]+//g;
$da cmp $db;
} @files;
open(FILE, ">
".$this_base."/".$FILE_NAME.".".$config{$this_base}{"ext"}) ||
die "Couldn't write file $FILE_NAME.".$config{$this_base}{"ext"}."
to $this_base";
print FILE ($config{$this_base}{"header"}."\n");
# print menu (if any)
print FILE ("$MENU_STR");
# start table
print FILE ($config{$this_base}{"table"}."\n");
#print all picts now
foreach(@files){
$this_file = basename($_);
if ($i == 0) {
# open a new row
# this row doesn't need bgcolor
if ( $config{$this_base}{"tr"} =~ m/\%+bgcolor\%+/i ) {
($config{$this_base}{"tr"} = $config{$this_base}{"tr"})
=~ s/\%+bgcolor\%+//i;
}
print FILE ($config{$this_base}{"tr"}."\n");
}
print FILE ("\t".$config{$this_base}{"td"}."\n");
($file_name = $this_file) =~ s/$EXT_INCL_EXPR//gi;
($file_name = $file_name) =~ s/^$THUMB_PREFIX//; # removes
prefix
# EXT is a global and so is THUMBNAIL
print FILE ("".
"\n");
print FILE ("\t
if ($i<($TD-1)) {
$i++;
} else {
# wrap and reset counter
print FILE ("
$i = 0;
}
} # end for e/a @files
# complete missing TD
if ($i != 0) {
for (;$i<$TD;$i++) {
print FILE ("\t".$config{$this_base}{"td"}."\n");
print FILE (" ");
print FILE ("\t
}
}
print FILE ("
print FILE ("
print FILE ($config{$this_base}{"footer"}."\n");
print FILE ("\n");
close(FILE);
} # end for e/a this_base
} # end mkindex
my $ROOT = $_[0];
my $MENU_STR = $_[1];
# locals: reset some locals
my (@ls,%pixfiles) = ();
my ($thisFile,
$pix_name,
$file_name,
$next_pix_name,
$next_file_name,
$last_pix_name,
$last_html_file,
$current_html_file,
$last_file_name,
$current_link,
$last_link,
$LAST_BASE,
$NEXT_BASE,
$HTMLSDIR) = "";
# these two are special...
# init to some strange string...
my $BASE = ",\/trash";
my $tmp_BASE = ",\/more_trash";
#construct array of all image files
my @ary = do_file_ary("$ROOT");
my %seen = ();
my @uniq = grep(!$seen{$_}++,@ary);
foreach (@uniq){
$thisFile = basename($_);
next if ($thisFile =~ m/$EXCEPTION_LIST/);
next if ($_ =~ m/\b$THUMBNAIL\b/i);
next if ($thisFile !~ m/$EXT_INCL_EXPR/i);
push @ls,$_;
#$TOTAL++;
} #end images array creation
# sort files alphabetically (dictionary order):
# maybe we should've sorted before we got here...
my $da;
my $db;
@ls = sort {
($da = lc $a) =~ s/[\W_]+//g;
($db = lc $b) =~ s/[\W_]+//g;
$da cmp $db;
} @ls;
# gauge message
my $MESSAGE = "Thumbnails Creation";
# initial values for gauge
# TOTAL -> number of elements in ls array
my ($PROGRESS,$TOTAL) = (0,( $#ls + 1 ) );
progressbar_msg($MESSAGE);
foreach(@ls)
{
$pix_name = basename($_);
# strip extension from file name
($file_name = $pix_name) =~ s/$EXT_INCL_EXPR//gi;
# get base directory
( $BASE = $_ ) =~ s/(.*)\/$pix_name$/$1/g;
# BASE is blank if we are already inside the directory
# for which to do thumbnails, thus:
if ( $BASE eq ""
|| ! -d $BASE )
{
$BASE = ".";
}
next if ($BASE eq $THUMBNAIL);
#print STDOUT $BASE."\n";
# warnings from Perl..
if ( $BASE gt ""
&& $tmp_BASE gt ""
&& $BASE !~ m/$tmp_BASE/ )
{
if (
$FORCE > 0 &&
! -f "$BASE/.nopixdir2htmlrc"
)
{
if (
copy("$ROOT_DIRECTORY/$CONFIG_FILE",
"$BASE/$CONFIG_FILE")
)
{
print $LOGFILE (": Force copy ".
" $ROOT_DIRECTORY/$CONFIG_FILE ".
"==> $BASE/$CONFIG_FILE \n");
} # end if copy
} # end if FORCE
)
{
if (
copy("$ROOT_DIRECTORY/$CONFIG_FILE",
"$BASE/$CONFIG_FILE")
)
{
print $LOGFILE (": Copied ".
" $ROOT_DIRECTORY/$CONFIG_FILE ".
"==> $BASE/$CONFIG_FILE \n");
} # end if copy
} # end if missing $CONFIG_FILE
if (! -f "$BASE/.nopixdir2htmlrc" && ! exists $config{$BASE} )
{
# change of base, reset two-dimensional array counter
print $LOGFILE "+ Reading config for $BASE\n";
# also init $config{$BASE} for us...
init_config($BASE);
} # end if not nopixdir2htmlrc
$total_directories++;
} # end if base not equal tmp_base
$tmp_BASE = $BASE;
next if ( -f "$BASE/.nopixdir2htmlrc" );
$THUMBNAILSDIR="$BASE/$THUMBNAIL";
if (!-d "$THUMBNAILSDIR") {
print $LOGFILE ("= Making thumbnail directory in $BASE\n");
mkdir("$THUMBNAILSDIR",0755);
}
print $LOGFILE ("\n= Converting file $BASE/$pix_name into
$THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name \n");
my $image = Image::Magick->new;
$image->Read("$BASE/$pix_name");
$image->Resize("$PERCENT");
$image->Write("$THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name");
undef $image;
# TODO if we could not load Image::Magick, see if "convert" is
installed and use
# this instead:
#system("convert -geometry $PERCENT $BASE/$pix_name
$THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name");
#if ( $? != 0 ) {
# die "ERROR: conversion failed\n $! ";
#}
print $LOGFILE ("\n");
}
# end if thumbnail file
push @{$pixfiles{$BASE}},
"$THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name";
# update flags
$LAST_BASE = $BASE;
# update progressbar
progressbar($PROGRESS,$TOTAL);
$PROGRESS++;
} #end foreach @ls
mkindex(\%pixfiles,$MENU_STR); # pass hash reference
# and a menu string
# to be included in e/a file
}
# creates an HTML page for a thumbnail
my $ROOT = $_[0];
# locals
my @ls = ();
my $i = 0;
my ($thisFile,
$pix_name,
$file_name,
$next_pix_name,
$next_file_name,
$last_pix_name,
$current_html_file,
$last_file_name,
$current_link,
$last_link,
$LAST_BASE,
$NEXT_BASE,
$HTMLSDIR) = "";
# TODO find a more elegant solution here
# init to dummy string:
my $BASE = "trash/\file";
my $tmp_BASE = "garbage\/file";
my $last_html_file = "this_is/dummy\string";
defined $pixfile[0]
&& -f $pixfile[0]
)
{
# copy that array instead:
@ary = @pixfile;
} else {
# construct array of all files
@ary = do_file_ary("$ROOT");
}
my %seen = ();
my @uniq = grep(!$seen{$_}++,@ary);
# from it:
foreach (@uniq){
$thisFile = basename($_);
next if ($thisFile =~ m/$EXCEPTION_LIST/);
next if ($_ =~ m/\/$THUMBNAIL\/.*$EXT_INCL_EXPR$/i);
next if ($thisFile !~ m/$EXT_INCL_EXPR/i);
push @ls,$_;
} #end images array creation
# TODO make this into a function and re-use it...
# sort files alphabetically (dictionary order):
# maybe we should've sorted before we got here...
my $da;
my $db;
@ls = sort {
($da = lc $a) =~ s/[\W_]+//g;
($db = lc $b) =~ s/[\W_]+//g;
$da cmp $db;
} @ls;
# gauge message
my $MESSAGE = "HTML Creation";
# initial values for gauge, note total
# is number of elements in array ;-)
my ($PROGRESS,$TOTAL) = (0,$#ls);
progressbar_msg($MESSAGE);
#print all picts now
# $#VAR gets number of elements of an array variable
for ( $i=0; $i <= $#ls; $i++) {
$pix_name = basename($ls[$i]);
# strip extension from file name
($file_name = $pix_name) =~ s/$EXT_INCL_EXPR//gi;
# get base directory
( $BASE = $ls[$i] ) =~ s/(.*)\/$pix_name$/$1/g;
# BASE is blank if we are already inside the directory
# for which to do thumbnails, thus:
if ( ! -d $BASE ) {
$BASE = ".";
}
next if ($BASE eq $THUMBNAIL);
# print STDOUT "Base: $BASE.\n";
if ( $BASE gt ""
&& $BASE ne $tmp_BASE )
{
# read specific config file for this directory
if (! -f "$BASE/.nopixdir2htmlrc")
{
if (! exists $config{$BASE} )
{
print $LOGFILE "+ Thumb_Html_Files Reading config for
$BASE\n";
init_config($BASE);
} # end if not exists config{base}
}
}
# update flag
$tmp_BASE = $BASE;
next if ( -f "$BASE/.nopixdir2htmlrc" );
# construct PATH for html directory
$HTMLSDIR = "$BASE/$HTMLDIR";
if (!-d "$HTMLSDIR") {
print $LOGFILE ("= Making HTML directory in $BASE\n");
mkdir("$HTMLSDIR",0755);
}
$current_html_file = "$HTMLSDIR/$file_name.".$config{$BASE}{"ext"};
$current_link = "$file_name.".$config{$BASE}{"ext"};
if ( -f $current_html_file ){
print $LOGFILE ": Overriding $current_html_file\n";
} # end if not current_html_file
print $LOGFILE ("= Creating html file into $current_html_file\n");
# TODO routine for creating file should be called here...
open(FILE, "> $current_html_file") ||
die "Couldn't write file $current_html_file";
print FILE ($config{$BASE}{"header"}."\n");
# start table
print FILE ($config{$BASE}{"table"}."\n");
print FILE ("
\n");
# image here
print FILE ("\n");
print FILE ("
# backward link here
if ( $last_html_file ne "this_is/dummy\string"
&& -f $last_html_file
&& ($BASE eq $LAST_BASE) )
{
print FILE ("<==\n");
} else {
print FILE ("<==");
}
# home link here
print FILE (" | HOME | \n");
$next_pix_name = "....";
# calculate next base
$next_pix_name = basename($ls[$i+1]);
# get next base directory
( $NEXT_BASE = $ls[$i+1] ) =~ s/(.*)\/$next_pix_name$/$1/g;
}
# forward link here
if ( -f $ls[$i+1] && ($BASE eq $NEXT_BASE) ) {
$next_file_name = "";
($next_file_name = $next_pix_name) =~ s/$EXT_INCL_EXPR//gi;
#print FILE ("==>");
print FILE ("==>\n");
} else {
print FILE ("==>");
# TODO would be nice to jump to next directory in the
# array...
#print FILE (" |=>>
\n");
}
print FILE ("
print FILE ($config{$BASE}{"footer"}."\n");
close(FILE);
# end HTML
print $LOGFILE ("\n");
# keep track of links
$last_html_file = $current_html_file;
$last_link = $current_link;
# update flags
$LAST_BASE = $BASE;
$NEXT_BASE = "";
#$PRINT_NEXT_LINK = 0;
progressbar($PROGRESS,$TOTAL);
$PROGRESS++;
} #end foreach
} # end thumb_html_files
#---------------------------------------------#
# It creates a menu.$EXT file at
# the root level of the picture
# directory (at the first
# directory that was passed to the script) or
# it puts a menu in e/a index.$EXT file
#
# if there is a file named .new
# inside the given directory,
# then a IMG tag will be put in
# front of the link with an image
# src=myscript{new} in it
#
# Thus in the config file put a line as such:
# new=http://images.server.com/new_icon.png;
#----------------------------------------------#
my $IMG = "";
my $line = "";
#my $thisFile= "";
my $x=0; # counts number of links
my $y=0; # counts number of td's
my $i=0; # general purpose counter
my $j=0; # count number of TR's
my @ls = ();
my $ts = "";
my @files=();
my @pixdir = (); # reset array
my %seen = ();
my @uniq = grep(!$seen{$_}++,@ary);
# check if a .nopixdir2htmlrc file exists
# if it does, then skip it and do the next one.
# if it doesn't, then assume this will contain
# a index.$EXT file and add it to the menu.
#
# TODO
# If we check whether the index.$EXT file exists
# first, then we get files with no menu table...
# We should find a way to correct this.
# Take into consideration that this function is called
# before we even attempt to build the index.$EXT files
# thus, that makes things kind of difficult a bit.
# So, we should check if at least one .jpg|.gif|.png
# file exists in the current $directory. That should
# be done by do_dir_ary above
#
foreach my $directory (@uniq){
next if (-f "$directory/.nopixdir2htmlrc");
!-f "$directory/.nopixdir2htmlrc"
) {
# note that @ls holds the HTML links...
# thus, paths are relative and not absolute here:
"$directory/$FILE_NAME.".$config{$ROOT_DIRECTORY}{"ext"}; # why not push()?
just to keep count I guess...
$x++;
}
}
$total_links = $x;
# print STDERR join(' ', @ls), "\n";
my $da;
my $db;
@ls = sort {
($da = lc $a) =~ s/[\W_]+//g;
($db = lc $b) =~ s/[\W_]+//g;
$da cmp $db;
} @ls;
open(FILE, ">
".$ROOT_DIRECTORY."/".$MENU_NAME.".".$config{$ROOT_DIRECTORY}{"ext"}) ||
die "Couldn't write file
$MENU_NAME.".$config{$ROOT_DIRECTORY}{"ext"}." to $ROOT_DIRECTORY";
}
# print header only if menuonly is set and we want to show
# the header/footer set in .pixdir2htmlrc
if ( $MENUONLY > 0 && $config{$ROOT_DIRECTORY}{"menuheader_footer"} > 0
) {
print FILE ($config{$ROOT_DIRECTORY}{"header"}."\n");
}
#
# When using nautilus we are off by one:
# TODO needs more testing
# if ( $nautilus_root gt "" )
# {
# $total_links-- ;
# }
{
if ( $MENUONLY > 0 )
{
print FILE ($config{$ROOT_DIRECTORY}{"table"}."\n");
}
$MENU_STR .= $config{$ROOT_DIRECTORY}{"table"}."\n";
# print all links now
my $tmp_tr = ""; # used to color the rows
while($x>0){
# temporarily turn off warnings
no warnings;
# TODO
# menu only routine: prints to a file... should merge
# with the str portion (see else)
#
if ( $MENUONLY > 0 ) {
if ($config{$ROOT_DIRECTORY}{"tr"}=~m/\%+bgcolor\%+/i){
if (($j % 2) == 0){
($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~
s/\%+bgcolor\%+/bgcolor=#efefef/i;
} else {
($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~
s/\%+bgcolor\%+//i;
}
print FILE ($config{$ROOT_DIRECTORY}{"tr"}."\n");
}
for ($y=1;$y<=$menu_td;$y++){
# close the TD tags
if ($y > 1) {
print FILE ("\t
}
print FILE ("\t".$config{$ROOT_DIRECTORY}{"td"}."\n");
# if link exists, otherwise leave it blank
# TODO there is a better way to do this... find
it...
($ts = $ls[$i]) =~
s#(.*)/$FILE_NAME.$config{$ROOT_DIRECTORY}{"ext"}#$1#gi;
# from nautilus one cannot pass arguments
# "--menuonly" but... just to keep things
# consistent...
# if number of characters is greater than $STR_LIMIT
# truncate $ts to a few characters.
if ( $nautilus_root gt "" ) {
( $ls[$i] = $ls[$i] ) =~ s,$nautilus_root/,,g;
( $ts = $ts ) =~ s,$nautilus_root/*,,g;
}
if ( $CUT_DIRS > 0 )
{
$ts = cut_dirs($ts,$CUT_DIRS);
}":""; # if .new
file
$ts = ucfirst($tmp_ts);
print FILE ("$IMG
$ts\n");
} else {
print FILE (" ");
}
$i++;
$x--;
} # end for $y
print FILE ("
$j++; # incr TR counter
} else {
# general menu routine
# TODO cleanup
if ($config{$ROOT_DIRECTORY}{"tr"}=~m/\%+bgcolor\%+/i){
if (($j % 2) == 0){
($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~
s/\%+bgcolor\%+/bgcolor=#efefef/i;
} else {
($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~
s/\%+bgcolor\%+//i;
}
$MENU_STR .= $tmp_tr."\n";
} else {
$MENU_STR .= $config{$ROOT_DIRECTORY}{"tr"}."\n";
}
for ($y=1;$y<=$menu_td;$y++){
# close the TD tags
if ($y > 1) {
$MENU_STR .= "\t
}
$MENU_STR .= "\t".$config{$ROOT_DIRECTORY}{"td"}."\n";
# menu entries
if ( $ls[$i] ne "" ) {
# if link exists, otherwise leave it blank
# TODO there is a better way to do this... find
it...
( $ts = $ls[$i]) =~
s,(.*)/$FILE_NAME.$config{$ROOT_DIRECTORY}{"ext"},$1,gi;
$IMG = (-f "$ts/.new") ? "":""; # if .new
file
# if number of characters is greater than $STR_LIMIT
# truncate $ts to a few characters.
if ( $nautilus_root gt "" ) {
( $ls[$i] = $ls[$i] ) =~ s,$nautilus_root/,,g;
( $ts = $ts ) =~ s,$nautilus_root/*,,g;
}
if ( $CUT_DIRS > 0 )
{
$ts = cut_dirs($ts,$CUT_DIRS);
}
$ts = ucfirst($tmp_ts);
# $ls tends to hold the whole filename path+filename
# we don't care about the whole path here...
$MENU_STR .= "$IMG
$ts\n";
} else {
$MENU_STR .= " ";
}
$i++;
$x--;
} # end for $y
$MENU_STR .= "
$j++; # incr TR counter
} # end if/else menuonly
}
if ( $MENUONLY > 0 ) {
print FILE ("
}
$MENU_STR .= "
} # end if total_links
else
{
print $LOGFILE (": Not a single link found\n");
}
# see previous notes on header
if ( $MENUONLY > 0 && $config{$ROOT_DIRECTORY}{"menuheader_footer"} > 0)
{
print FILE ($config{$ROOT_DIRECTORY}{"footer"}."\n");
}
if ( $MENUONLY > 0 ) {
close(FILE);
}
if ( $total_links > 1 ) {
print $LOGFILE (": $total_links links in menu.\n");
}
return $MENU_STR;
} #end menu_file
{
my $str = shift;
my $str_length = length ($str);
$str = ($str_length > $STR_LIMIT) ?
"...".substr($str,($STR_LIMIT/2),$str_length):$str;
# return truncated string
return $str;
} #end str_truncate
{
my ($PROGRESS,$TOTAL)=@_;
chomp($PROGRESS);
chomp($TOTAL);
my $current = 0;
# make sure we don't divide by 0
if ( $TOTAL > 0 )
{
$current = sprintf( "%02d",($PROGRESS/$TOTAL) * 100 );
print $GAUGE $current."\n";
}
} # end progressbar
{
my ($MESSAGE) = @_;
print $GAUGE "XXX\n".$MESSAGE."\nXXX\n";
} # end progressbar_msg
# uses find() to recur thru directories
# returns an array of directories
# i.e. in directory "a" with structure:
# /a
# /a/b
# /a/b/c
# /a/b2/c2
#
# my @ary = &do_dir_ary(".");
#
# will yield:
# a
# a/b
# a/b/c
# a/b2/c2
#
my %opt = (wanted => \&process_dir, no_chdir=>1);
find(\%opt,$ROOT);
return @pixdir;
} # end do_dir_ary
my $base_name = basename($_);
if (
!-f $_
&& $base_name !~ m/^($EXCEPTION_LIST)$/
&& $base_name !~ m/\b$THUMBNAIL\b/
&& $base_name !~ m/\b$HTMLDIR\b/
&& $base_name !~ m/^\.[a-zA-Z0-9]+$/
)
{
s/^\.\/*//g;
push @pixdir,$_;
#print $_ . "\n";
}
} # end process_dir
# uses find() to recur thru directories
# returns an array of files
# i.e. in directory "a" with the files:
# /a/file.txt
# /a/b/file-b.txt
# /a/b/c/file-c.txt
# /a/b2/c2/file-c2.txt
#
# my @ary = &do_file_ary(".");
#
# will yield:
# a/file.txt
# a/b/file-b.txt
# a/b/c/file-c.txt
# a/b2/c2/file-c2.txt
#
my $ROOT = shift;
my %opt = (wanted => \&process_file, no_chdir=>1);
find(\%opt,$ROOT);
return @pixfile;
} # end do_file_ary
my $base_name = basename($_);
if (
-f $_
&& $base_name !~ m/^($EXCEPTION_LIST)$/
&& $base_name !~ m/\b$THUMBNAIL\b/
&& $base_name !~ m/\b$HTMLDIR\b/
&& $base_name !~ m/^\.[a-zA-Z0-9]+$/
)
{
s/^\.\/*//g;
push @pixfile,$_;
}
} #end process_file
# call like cut_dirs($ts,$CUT_DIRS);
# where ts is a path in the form "path/to/something"
# and $CUT_DIRS is an integer
my $path = shift;
my $cut = shift;
# TODO is there a way to know the OS separator string in Perl
# a la Python?
$path =~ s,^/,,g; # remove leading slashes
my @tmp_path = split(/\//,$path);
my $tmp_str = "";
{
$tmp_str .= $tmp_path[$i]."/";
}
}
return $tmp_str;
} # end cut_dirs
==== nautilus-scripts/Varios/FileProcessing/pprint ====
$ cat nautilus-scripts/Varios/FileProcessing/pprint
#!/bin/sh
# Copyright (C) Sept 13, 2001 Shane Mueller
# http://g-scripts.sourceforge.net
#
# pprint: This script designed for use with the Nautilus File Manager
# This script requires the unix utility enscript, and may require
# modification based upon your local printing command.
# It will either print directly to the default printer or
# will generate a pretty file from the selected text files, and either
# print to printer or generate files from selected files.
#
# This does file-type sensitive selection.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#First, process each of the selected file
for arg
do
filetype=$(file "$arg")
#Do file-type sensitive processing
case "$filetype" in
*text*) #Any type of Text file
#This allows you to select how the file is processed
choice=`gdialog --menu "How should I process this file?" 200 200 4 '1' "Print" '2' "Make .ps" '3' "Make .html" '4' "Make .rtf" 2>&1`
case $choice in
1) ##print using enscript
enscript -2 -G2rE -U1 --borders --word-wrap "$arg"
;;
2) ##print to a .ps file of your choice
NEWNAME=`gdialog --title "Generate Postscript File" --inputbox "Enter Filename (include extension)" 200 100 "$arg".ps 2>&1`
enscript -2 -G2rE -U1 --borders --word-wrap -p "$NEWNAME" "$arg"
;;
3) ##Generate an .html
NEWNAME=`gdialog --title "Generate .html" --inputbox "Enter Filename (include extension)" 200 100 "$arg".html 2>&1`
enscript -E --color -W html -p "$NEWNAME" "$arg"
;;
4) ##Generate an .rtf
NEWNAME=`gdialog --title "Generate .rtf" --inputbox "Enter Filename (include extension)" 200 100 "$arg".rtf 2>&1`
enscript -E -W rtf -p "$NEWNAME" "$arg"
;;
*) ##Don't do nothing-cancel key
;;
esac
;;
*postscript*) ##send to printer directly
lpr "$arg"
;;
##Other file types can go here if you know how to process them.
*)
gdialog --msgbox "Uncertain how to process file $arg: \n File type $filetype" 200 200
esac
done
==== nautilus-scripts/Varios/FileProcessing/print ====
$ cat nautilus-scripts/Varios/FileProcessing/print
#!/bin/bash
# FILE: print --
# AUTHOR: W. Michael Petullo
# DATE: 31 May 2001
#
# Copyright (C) 2001 W. Michael Petullo
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
lpr $*
==== nautilus-scripts/Varios/FileProcessing/print_with_openoffice ====
$ cat nautilus-scripts/Varios/FileProcessing/print_with_openoffice
#!/bin/sh
#
# This script prints the selected files with openoffice.org
# especially useful for openoffice files ;-)
#
# the "quoted..." line handles multiple files with spaces
# (like shown on the g-scripts site)
#
quoted=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | awk 'BEGIN {FS = "\n" } { printf "\"%s\" ", $1 }' | sed -e s#\"\"##)
eval "ooffice -p $quoted"
==== nautilus-scripts/Varios/FileProcessing/ps2pdf ====
$ cat nautilus-scripts/Varios/FileProcessing/ps2pdf
#!/bin/sh
cd $NAUTILUS_SCRIPT_CURRENT_URI
ps2pdf $@
==== nautilus-scripts/Varios/FileProcessing/scp2host ====
$ cat nautilus-scripts/Varios/FileProcessing/scp2host
#!/bin/sh
#scp to host
Eterm --trans --shade 40 --scrollbar off --menubar off -e scp $@ user@host:~
==== nautilus-scripts/Varios/FileProcessing/scp_to_host ====
$ cat nautilus-scripts/Varios/FileProcessing/scp_to_host
#!/bin/sh
#
# This script scp's file/s to a given url.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Keith Conger
#
# Install in your ~/Nautilus/scripts directory.
# You need to be running Nautilus 1.0.3 +
URL=$(gdialog --title "scp file(s) to?" --inputbox "url for host(ie.user@myhost.com:/tmp)" 200 550 2>&1)
gnome-terminal -t "Copying file.." -x scp $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $URL
==== nautilus-scripts/Varios/FileProcessing/search_n_replace ====
$ cat nautilus-scripts/Varios/FileProcessing/search_n_replace
#!/bin/bash
# FILE: search_n_replace --
# AUTHOR: W. Michael Petullo
# DATE: 31 May 2001
#
# Copyright (C) 2001 W. Michael Petullo
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
SEARCH=`gdialog --title "Search For" --inputbox "Regular Expression" 200 450 2>&1`
REPLACE=`gdialog --title "Replace With" --inputbox "String" 200 450 2>&1`
TMP=`mktemp /tmp/search_n_replace.XXXXXX`
trap 'rm -f $TMP' EXIT SIGHUP SIGINT SIGTERM
for file in $*; do
sed -e "s/$SEARCH/$REPLACE/g" $file > $TMP
cp $file $file.bak
mv $TMP $file
done
==== nautilus-scripts/Varios/FileProcessing/secure_copy ====
$ cat nautilus-scripts/Varios/FileProcessing/secure_copy
#!/bin/bash
###############################################################################
# secure copy (scp) Files to a given location
###############################################################################
#
# AUTHOR: Brian Connelly
# DESCRIPTION: This script does what its name implies-- it copies the files
# which have been selected in Nautilus to a remote or local
# location using the scp command.
#
# REQUIREMENTS: Nautilus file manager
# scp (see OpenSSH)
# gdialog, which is usually included in the gnome-utils package
#
# INSTALLATION: GNOME 1.4.x: copy this script to the ~/Nautilus/scripts
# directory
# GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory
#
# USAGE: Select the files that you would like to copy in Nautilus,
# right click, go to Scripts, and then select this script.
# You will then be asked to select a target destination.
# This can be one of the following:
#
# Ex. 1. /tmp - copy the selected files to /tmp ON THIS MACHINE
# Ex. 2. something.com:/home/somegyy - copy the selected files
# to /home/someguy directory on the machine something.com.
# NOTE: Your username on that machine must either be the
# same as your username on the local machine as on
# something.com, or the proper username must be
# specified in the .ssh_hosts file
# Ex. 3. someguy@something.com:/home/someguy - copy the selected
# files to /home/someguy on something.com. Your username
# on something.com is someguy.
#
# VERSION INFO:
# 0.1 (20020923) - Initial public release
#
# COPYRIGHT: Copyright (C) 2002 Brian Connelly
#
# LICENSE: GNU GPL
#
###############################################################################
SCRIPT_TITLE=$(basename "$0")
SCP_BIN=$(which scp) || (gdialog --title "$SCRIPT_TITLE Error" --msgbox "scp
cannot be found. It is either not in your PATH or not installed on this
system" 400 400 2>&1 && exit)
TARGET=""
if [ -z $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then
gdialog --title "$SCRIPT_TITLE Error" --msgbox "No files have been selected"
400 400 2>&1
exit
fi
while [ -z $TARGET ]
do
TARGET=$(gdialog --title "$SCRIPT_TITLE" --inputbox "Enter Target
Destination:" 400 400 "" 2>&1) || exit
if [ -z $TARGET]; then
gdialog --title "$SCRIPT_TITLE Error" --msgbox "You must choose a target
destination" 400 400 2>&1
fi
done
($SCP_BIN -r $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $TARGET >&
/tmp/scripterror && rm /tmp/scripterror) || (gdialog --title "$SCRIPT_TITLE
Error" --msgbox "Could not execute scp: `cat /tmp/scripterror`" 400 400 2>&1
&& rm /tmp/scripterror)
==== nautilus-scripts/Varios/FileProcessing/superexec.py ====
$ cat nautilus-scripts/Varios/FileProcessing/superexec.py
#!/usr/bin/env python
"""
superexec -- Nautilus script for building command pipelines
Version: 0.1
Requitements: python, pygtk2
Copyright (C) 2002 Krzysztof Luks
Distributed under the terms of GNU GPL version 2 or later
This script allows building complicated command pipelines without need
to use shell. Commands will be executed in following order:
command1
Output can be saved to file, printed on screen or sent to last command
in pipeline.
Some tips:
- superexec can also be used to run single command (e.g. fortune)
- if you want to send selected file to stdin of the first command
append '<' character to it's name (e.g. 'wc -l <')
- if you want to do the above for multiple files use cat as the
first command
- be careful with potentialy dangerus commands like rm
- all feedback is welcome :)
Caveats:
- needs testing!
- script freezes until pipeline is completed (don't try to run commands
that dont return (e.g. lynx)
- new entries can only be added at the end of pipeline
- save doesn't work
Changes:
0.1 (2003.02.01) -- initial release
TODO:
- find a better name for the script
- add new entry after current one
- allow to process multiple files one by one or all at once
- add more error checking
- run commands in background and make it possible to interrupt them
- change 0 and ton to gtk.FALSE and gtk.TRUE
- saving output to file
- printting output
- clear entry ? clear all ?
- better documentation
- you name it!
"""
import os
import string
import pygtk ; pygtk.require('2.0')
import gtk
def parse_nautilus_environment():
result = {
'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' : [],
'NAUTILUS_SCRIPT_SELECTED_URIS' : [],
'NAUTILUS_SCRIPT_CURRENT_URI' : [],
'NAUTILUS_SCRIPT_WINDOW_GEOMETRY' : [] # I wonder if anyone uses it ;)
}
for i in result.keys():
if os.environ.has_key(i):
result[i] = os.environ[i].split(':')
else:
result[i] = []
return result
def destroy_cb(widget, data = None):
gtk.main_quit()
def add_row_cb(widget, data = None):
hbox = gtk.HBox(gtk.FALSE, 0)
entry = gtk.Entry(max = 0)
entries.append(entry)
hbox.pack_start(entry)
hbox.pack_start(gtk.VSeparator(), gtk.FALSE, gtk.TRUE, 5)
button = gtk.Button(stock = gtk.STOCK_ADD)
button.connect('clicked', add_row_cb)
hbox.pack_start(button)
button = gtk.Button(stock = gtk.STOCK_REMOVE)
if len(entries) > 1:
button.connect('clicked', del_row_cb, hbox)
else:
button.set_sensitive(gtk.FALSE)
hbox.pack_start(button)
entrybox.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)
hbox.show_all()
def del_row_cb(widget, data = None):
entry = data.get_children()[0]
entries.remove(entry)
entrybox.remove(data)
def execute_cb(widget, data = None):
str = entries[0].get_text() + ' '
paths = parse_nautilus_environment()['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS']
for path in paths:
str += string.strip(path) + ' '
if len(entries) == 2:
str += ' | ' + entries[-1].get_text()
elif len(entries) > 2:
str += ' | '
for e in range(1, len(entries)-1):
str += entries[e].get_text() + ' | '
str += entries[-1].get_text()
import tempfile
tmp_out = None
tmp_err = tempfile.mktemp('superexec')
str += ' 2> ' + tmp_err
if lr[-1] == 'file':
str += ' > ' + file_entry.get_text()
elif lr[-1] == 'show':
tmp_out = tempfile.mktemp('superexec')
str += ' > ' + tmp_out
decision = show_dialog(gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, str)
print 'I would execeute: ',
print str
if decision == gtk.RESPONSE_OK:
res = os.system(str)
if res < 0:
show_dialog(gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Fork failed')
elif res > 0:
f = open(tmp_err)
msg = ''
for line in f.readlines():
msg += line
f.close()
show_dialog(gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, msg)
elif lr[-1] == 'show':
show_output(tmp_out)
os.remove(tmp_err)
os.remove(tmp_out)
def button_cb(widget, data = None):
print data
def radio_cb(widget, data = None):
if data == 'file' and widget.get_active():
file_entry.set_sensitive(1)
file_button.set_sensitive(1)
else:
file_entry.set_sensitive(0)
file_button.set_sensitive(0)
lr.pop()
lr.append(data)
def make_buttons():
box = gtk.VBox(gtk.FALSE, 0)
hbox = gtk.HBox(gtk.FALSE, 0)
widget = gtk.RadioButton(None, 'show')
widget.connect('toggled', radio_cb, 'show')
widget.set_active(1)
group = widget
hbox.pack_start(widget)
widget = gtk.RadioButton(group, 'last command')
widget.connect('toggled', radio_cb, 'last')
hbox.pack_start(widget)
widget = gtk.RadioButton(group, 'file')
widget.connect('toggled', radio_cb, 'file')
hbox.pack_start(widget)
box.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)
hbox = gtk.HBox(gtk.FALSE, 0)
widget = gtk.Entry(max = 0)
f_entry = widget
f_entry.set_sensitive(0)
hbox.pack_start(widget)
widget = gtk.Button(label = 'Browse...')
f_button = widget
f_button.set_sensitive(0)
widget.connect('clicked', execute_cb)
hbox.pack_start(widget)
box.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)
hbox = gtk.HBox(gtk.FALSE, 0)
widget = gtk.Button(stock = gtk.STOCK_EXECUTE)
widget.connect('clicked', execute_cb)
hbox.pack_start(widget)
widget = gtk.Button(stock = gtk.STOCK_CLOSE)
widget.connect('clicked', destroy_cb)
hbox.pack_start(widget)
box.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)
return box, f_entry, f_button
def show_dialog(type, buttons, str):
dialog = gtk.MessageDialog(win,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
type, buttons, str)
result = dialog.run()
dialog.destroy()
return result
def show_output(file):
dialog = gtk.Dialog("Command output", win, 0,
(gtk.STOCK_SAVE_AS, gtk.RESPONSE_OK,
gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL))
buff = gtk.TextBuffer(None)
f = open(file)
for line in f.readlines():
buff.insert_at_cursor(line, len(line))
f.close()
tv = gtk.TextView()
tv.set_buffer(buff)
tv.set_editable(gtk.FALSE)
tv.set_cursor_visible(gtk.FALSE)
sw = gtk.ScrolledWindow()
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
sw.set_shadow_type(gtk.SHADOW_IN)
sw.add(tv)
dialog.vbox.pack_start(sw, gtk.TRUE, gtk.TRUE, 0)
dialog.set_default_size(640, 480)
dialog.show_all()
result = dialog.run()
dialog.destroy()
return result
entries = []
lr = ['show']
win = gtk.Window()
win.set_title('superexec')
win.connect("delete_event", destroy_cb)
win.set_border_width(5)
buttonbox, file_entry, file_button = make_buttons()
entrybox = gtk.VBox(gtk.FALSE, 0)
entrybox.set_border_width(5)
frame1 = gtk.Frame('Command chain')
frame1.add(entrybox)
frame2 = gtk.Frame('Output')
frame2.add(buttonbox)
mainbox = gtk.VBox(gtk.FALSE, 0)
mainbox.pack_start(frame1)
mainbox.pack_start(frame2)
win.add(mainbox)
add_row_cb(None)
geom = parse_nautilus_environment()['NAUTILUS_SCRIPT_WINDOW_GEOMETRY']
if len(geom) > 0:
geom = geom[0]
geom = geom.replace('x', '+').split('+')
# position script window in the center of current nautilus window
x = (int(geom[0]) / 2) + int(geom[2])
y = (int(geom[1]) / 2) + int(geom[3])
win.move(x, y)
win.show_all()
gtk.main()
==== nautilus-scripts/Varios/FileSystemManagement/burn_dir ====
$ cat nautilus-scripts/Varios/FileSystemManagement/burn_dir
#!/bin/bash
# FILE: burn_dir --
# AUTHOR: W. Michael Petullo
# DATE: 31 May 2001
#
# Copyright (C) 2001 W. Michael Petullo
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
bbbdir -v "$1" -i "$1" | bbb -s 4 -x
==== nautilus-scripts/Varios/FileSystemManagement/burn_iso ====
$ cat nautilus-scripts/Varios/FileSystemManagement/burn_iso
#!/bin/sh
# Placed into the Public Domain 2/2002 by Shane T. Mueller
# This will use cdrecord to burn an .iso file to your ard-coded
# cd-rom writer
# You should do a cdrecord -scanbus to determine the dev setting
# for your cd-rom writing device. For me, it looked like this:
# $ cdrecord -scanbus
# Cdrecord 1.10 (i686-pc-linux-gnu) Copyright (C) 1995-2001 J\F6rg Schilling
# Linux sg driver version: 3.1.22
# Using libscg version 'schily-0.5'
# scsibus0:
# 0,0,0 0) 'IOMEGA ' 'ZIP 100 ' '13.A' Removable Disk
# 0,1,0 1) 'HP ' 'CD-Writer+ 8100 ' '1.0g' Removable CD-ROM
# 0,2,0 2) *
# 0,3,0 3) *
# 0,4,0 4) *
# 0,5,0 5) *
# 0,6,0 6) *
# 0,7,0 7) *
#
# I chose dev=0,1,0. speed can also be adjusted to suit your needs.
cdrecord -v -data dev=0,1,0 speed=8 $1
==== nautilus-scripts/Varios/FileSystemManagement/change_name ====
$ cat nautilus-scripts/Varios/FileSystemManagement/change_name
#!/bin/bash
search=`gdialog --title "Rename files" --inputbox "Search for" 200 450 2>&1` || exit
replace=`gdialog --title "Rename files" --inputbox "Replace with" 200 450 2>&1` || exit
path=`echo -n "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | head -n 1 | sed 's/[^\/]*$//'`
while [ $# -gt 0 ]; do
newname=`echo "$1" | sed -e "s/$search/$replace/g"`
mv "$path$1" "$path$newname"
shift
done
==== nautilus-scripts/Varios/FileSystemManagement/chmod ====
$ cat nautilus-scripts/Varios/FileSystemManagement/chmod
#!/usr/bin/perl
#
# A GUI for chown, chgrp and chmod. Requires perl and perl-gtk
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) David Westlund
#
my $false = 0;
my $true = 1;
use Gtk;
init Gtk;
# Widgets
my $window;
my $signal;
my $main_vbox;
my $user_table_alignment;
my $user_table;
my $user_label;
my $user_entry;
my $group_label;
my $group_entry;
my $separator1;
my $chmod_table_alignment;
my $chmod_table;
my $user_chmod_label_alignment;
my $user_chmod_label;
my $group_chmod_label_alignment;
my $group_chmod_label;
my $others_chmod_label_alignment;
my $others_chmod_label;
my $read_label;
my $user_read_button;
my $group_read_button;
my $others_read_button;
my $write_label;
my $user_write_button;
my $group_write_button;
my $others_write_button;
my $execute_label;
my $user_execute_button;
my $group_execute_button;
my $others_execute_button;
my $separator2;
my $file_info_hbox_alignment;
my $file_info_hbox;
my $permission_vbox;
my @permissions;
my $owner_vbox;
my @owners_alignment;
my @owners;
my $group_vbox;
my @groups_alignment;
my @groups;
my $filename_vbox;
my @filenames_alignment;
my @filenames;
# Non-widgets (used in the ls-loop)
my $file_info;
my $rights;
my $name;
my $separator3;
my $last_hbox;
my $ok_button;
my $cancel_button;
# Not widgets...
my $id;
my $user;
#my @groups;
# Fix info about the user and the groups
$id = `id`;
$user = $id;
$user =~ s/^[^\(]+\(//;
$user =~ s/\).*//s;
# I don't use the code for groups now, but it may be handy
# in the future...
#@groups = split ",", $id;
#$groups[0] =~ s/.*gid[^\(]+\(.*\(//;
#$groups[0] =~ s/\).*//;
#foreach (@groups) {
#$_ =~ s/.*\(//;
#$_ =~ s/\).*//s;
#}
# Create the gtk-program
$window = new Gtk::Window ( 'toplevel' );
$signal = $window->signal_connect ('delete_event',
sub { Gtk->exit (0); } );
$window->border_width (5);
$window->set_title ("Chmod");
$main_vbox = new Gtk::VBox ($false, 0);
$window->add ($main_vbox);
$main_vbox->show ();
# The table for owners and groups.
$user_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);
$user_table = new Gtk::Table (2, 2, $true);
$user_table_alignment->add ($user_table);
$main_vbox->pack_start ($user_table_alignment, $false, $false, 0);
$user_table_alignment->show ();
$user_table->show ();
# Create the owners and groups row.
if ($user =~ /^root$/) {
$user_label = new Gtk::Label ("owner: ");
$user_table->attach ($user_label, 0, 1, 0, 1, "fill", 0, 0, 0);
$user_label->show ();
$user_entry = new Gtk::Entry ( 10 );
$user_entry->set_usize (60, undef);
$user_table->attach ($user_entry, 1, 2, 0, 1, "fill", 0, 0, 0);
$user_entry->show ();
}
$group_label = new Gtk::Label ("group: ");
$user_table->attach ($group_label, 0, 1, 1, 2, "fill", 0, 0, 0);
$group_label->show ();
$group_entry = new Gtk::Entry ( 10 );
$group_entry->set_usize (60, undef);
$user_table->attach ($group_entry, 1, 2, 1, 2, "fill", 0, 0, 0);
$group_entry->show ();
$separator1 = new Gtk::HSeparator ();
$main_vbox->pack_start ($separator1, $true, $true, 10);
$separator1->show ();
# Time for the chmod-section
$chmod_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);
$chmod_table = new Gtk::Table (4, 4, $true);
$chmod_table_alignment->add ($chmod_table);
$main_vbox->pack_start ($chmod_table_alignment, $false, $false, 0);
$chmod_table->set_col_spacings ( 0 );
$chmod_table_alignment->show ();
$chmod_table->show ();
# Adding the labels to the chmod_table
$user_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);
$user_chmod_label = new Gtk::Label ("user:");
$user_chmod_label_alignment->add ($user_chmod_label);
$chmod_table->attach ($user_chmod_label_alignment, 0, 1, 1, 2,"fill", 0, 0, 0);
$user_chmod_label_alignment->show ();
$user_chmod_label->show ();
$group_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);
$group_chmod_label = new Gtk::Label ("group:");
$group_chmod_label_alignment->add ($group_chmod_label);
$chmod_table->attach ($group_chmod_label_alignment,0, 1, 2, 3,"fill", 0, 0, 0);
$group_chmod_label_alignment->show ();
$group_chmod_label->show ();
$others_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);
$others_chmod_label = new Gtk::Label ("others:");
$others_chmod_label_alignment->add ($others_chmod_label);
$chmod_table->attach ($others_chmod_label_alignment,0, 1, 3, 4,"fill", 0, 0, 0);
$others_chmod_label_alignment->show ();
$others_chmod_label->show ();
# Adding the labels and the buttons to the read_vbox
$read_label = new Gtk::Label ("read");
$chmod_table->attach ($read_label, 1, 2, 0, 1, 0, 0, 0, 0);
$read_label->show ();
$user_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_read_button, 1, 2, 1, 2, 0, 0, 0, 0);
$user_read_button->show ();
$group_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_read_button, 1, 2, 2, 3, 0, 0, 0, 0);
$group_read_button->show ();
$others_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_read_button, 1, 2, 3, 4, 0, 0, 0, 0);
$others_read_button->show ();
# Adding the labels and the buttons to the write_vbox
$write_label = new Gtk::Label ("write");
$chmod_table->attach ($write_label, 2, 3, 0, 1, 0, 0, 0, 0);
$write_label->show ();
$user_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_write_button, 2, 3, 1, 2, 0, 0, 0, 0);
$user_write_button->show ();
$group_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_write_button, 2, 3, 2, 3, 0, 0, 0, 0);
$group_write_button->show ();
$others_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_write_button, 2, 3, 3, 4, 0, 0, 0, 0);
$others_write_button->show ();
# Adding the labels and the buttons to the execute_vbox
$execute_label = new Gtk::Label ("execute");
$chmod_table->attach ($execute_label, 3, 4, 0, 1, 0, 0, 0, 0);
$execute_label->show ();
$user_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_execute_button, 3, 4, 1, 2, 0, 0, 0, 0);
$user_execute_button->show ();
$group_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_execute_button, 3, 4, 2, 3, 0, 0, 0, 0);
$group_execute_button->show ();
$others_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_execute_button, 3, 4, 3, 4, 0, 0, 0, 0);
$others_execute_button->show ();
$separator2 = new Gtk::HSeparator ();
$main_vbox->pack_start ($separator2, $true, $true, 10);
$separator2->show ();
# Creating the list with filenames and permissions
$file_info_hbox_alignment = new Gtk::Alignment (0.5,0,0,0);
$file_info_hbox = new Gtk::HBox ($false, 0);
$file_info_hbox_alignment->add ($file_info_hbox);
$main_vbox->pack_start ($file_info_hbox_alignment, $false, $false, 0);
$file_info_hbox_alignment->show ();
$file_info_hbox->show ();
$permission_vbox = new Gtk::VBox ($fase, 0);
$file_info_hbox->pack_start ($permission_vbox, $false, $false, 20);
$permission_vbox->show ();
$owner_vbox = new Gtk::VBox ($false, 0);
$file_info_hbox->pack_start ($owner_vbox, $false, $false, 10);
$owner_vbox->show ();
$group_vbox = new Gtk::VBox ($false, 0);
$file_info_hbox->pack_start ($group_vbox, $false, $false, 10);
$group_vbox->show ();
$filename_vbox = new Gtk::VBox ($false, 0);
$file_info_hbox->pack_start ($filename_vbox, $false, $false, 20);
$filename_vbox->show ();
$i = 0;
foreach ( @ARGV ) {
$file_info = `ls -ld \"$_\"`;
chop $file_info;
$rights = $file_info;
$rights =~ s/\s.*//;
$owner = $file_info;
$owner =~ s/\S+\s+\S+\s+//;
$owner =~ s/\s.*//;
$group = $file_info;
$group =~ s/\S+\s+\S+\s+\S+\s+//;
$group =~ s/\s.*//;
$name = $file_info;
$name =~ s/\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+//;
$permissions[$i] = new Gtk::Label ("$rights");
$permission_vbox->pack_start ($permissions[$i], $false, $false, 0);
$permissions[$i]->show ();
$owners_alignment[$i] = new Gtk::Alignment (0,1,0,0);
$owners[$i] = new Gtk::Label ("$owner");
$owners_alignment[$i]->add ($owners[$i]);
$owner_vbox->pack_start ($owners_alignment[$i],$false, $false, 0);
$owners_alignment[$i]->show ();
$owners[$i]->show ();
$groups_alignment[$i] = new Gtk::Alignment (0,1,0,0);
$groups[$i] = new Gtk::Label ("$group");
$groups_alignment[$i]->add ($groups[$i]);
$group_vbox->pack_start ($groups_alignment[$i],$false, $false, 0);
$groups_alignment[$i]->show ();
$groups[$i]->show ();
$filenames_alignment[$i] = new Gtk::Alignment (0,1,0,0);
$filenames[$i] = new Gtk::Label ("$name");
$filenames_alignment[$i]->add ($filenames[$i]);
$filename_vbox->pack_start ($filenames_alignment[$i],$false, $false, 0);
$filenames_alignment[$i]->show ();
$filenames[$i]->show ();
$i++;
}
$separator3 = new Gtk::HSeparator ();
$main_vbox->pack_start ($separator3, $true, $true, 10);
$separator3->show ();
#This is the last line of widgets in the program...
$last_hbox = new Gtk::HBox ( $false, 0);
$main_vbox->pack_start ($last_hbox, $false, $false, 5);
$last_hbox->show ();
$ok_button = new Gtk::Button ("Ok");
$last_hbox->pack_start ($ok_button, $false, $false, 10);
$ok_button->signal_connect ('clicked', \&chmod);
$ok_button->show;
$cancel_button = new Gtk::Button ("Cancel");
$last_hbox->pack_start ($cancel_button, $false, $false, 10);
$cancel_button->signal_connect ('clicked', sub { Gtk->exit (0) } );
$cancel_button->show ();
$window->show ();
main Gtk;
exit (1);
sub chmod
{
my $mode = 0;
my $recursive = "";
my $files = "";
$mode += 400 if $user_read_button->active;
$mode += 200 if $user_write_button->active;
$mode += 100 if $user_execute_button->active;
$mode += 40 if $group_read_button->active;
$mode += 20 if $group_write_button->active;
$mode += 10 if $group_execute_button->active;
$mode += 4 if $others_read_button->active;
$mode += 2 if $others_write_button->active;
$mode += 1 if $others_execute_button->active;
$mode = "0" . $mode while length $mode < 3;
foreach (@ARGV) {
$files .= "\"$_\"" . " ";
}
system ("chmod $mode $files");
Gtk->exit ( 0 );
}
==== nautilus-scripts/Varios/FileSystemManagement/chmog ====
$ cat nautilus-scripts/Varios/FileSystemManagement/chmog
#!/usr/bin/perl
#
# A GUI for chown, chgrp and chmod. Requires perl and perl-gtk
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) David Westlund
#
my $false = 0;
my $true = 1;
use Gtk;
init Gtk;
# Widgets
my $window;
my $signal;
my $main_vbox;
my $user_table_alignment;
my $user_table;
my $user_label;
my $user_entry;
my $group_label;
my $group_entry;
my $separator1;
my $chmod_table_alignment;
my $chmod_table;
my $user_chmod_label_alignment;
my $user_chmod_label;
my $group_chmod_label_alignment;
my $group_chmod_label;
my $others_chmod_label_alignment;
my $others_chmod_label;
my $read_label;
my $read_plus_label;
my $read_minus_label;
my $user_plus_read_button;
my $user_minus_read_button;
my $group_plus_read_button;
my $group_minus_read_button;
my $others_plus_read_button;
my $others_minus_read_button;
my $write_label;
my $write_plus_label;
my $write_minus_label;
my $user_plus_write_button;
my $user_minus_write_button;
my $group_plus_write_button;
my $group_minus_write_button;
my $others_plus_write_button;
my $others_minus_write_button;
my $execute_label;
my $execute_plus_label;
my $execute_minus_label;
my $user_plus_execute_button;
my $user_minus_execute_button;
my $group_plus_execute_button;
my $group_minus_execute_button;
my $others_plus_execute_button;
my $others_minus_execute_button;
my $separator2;
my $file_info_hbox_alignment;
my $file_info_hbox;
my $permission_vbox;
my @permissions;
my $owner_vbox;
my @owners_alignment;
my @owners;
my $group_vbox;
my @groups_alignment;
my @groups;
my $filename_vbox;
my @filenames_alignment;
my @filenames;
# Non-widgets (used in the ls-loop)
my $file_info;
my $rights;
my $name;
my $separator3;
my $last_hbox;
my $recursice_button;
my $ok_button;
my $cancel_button;
# Not widgets...
my $id;
my $user;
#my @groups;
# Fix info about the user and the groups
$id = `id`;
$user = $id;
$user =~ s/^[^\(]+\(//;
$user =~ s/\).*//s;
# I don't use the code for groups now, but it may be handy
# in the future...
#@groups = split ",", $id;
#$groups[0] =~ s/.*gid[^\(]+\(.*\(//;
#$groups[0] =~ s/\).*//;
#foreach (@groups) {
#$_ =~ s/.*\(//;
#$_ =~ s/\).*//s;
#}
# Create the gtk-program
$window = new Gtk::Window ( 'toplevel' );
$signal = $window->signal_connect ('delete_event',
sub { Gtk->exit (0); } );
$window->border_width (5);
$window->set_title ("Chmog");
$main_vbox = new Gtk::VBox ($false, 0);
$window->add ($main_vbox);
$main_vbox->show ();
# The table to put owner and group in
$user_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);
$user_table = new Gtk::Table (2, 2, $true);
$user_table_alignment->add ($user_table);
$main_vbox->pack_start ($user_table_alignment, $false, $false, 0);
$user_table_alignment->show ();
$user_table->show ();
# Create the owners and groups row.
if ($user =~ /^root$/) {
$user_label = new Gtk::Label ("owner: ");
$user_table->attach ($user_label, 0, 1, 0, 1, "fill", 0, 0, 0);
$user_label->show ();
$user_entry = new Gtk::Entry ( 10 );
$user_entry->set_usize (60, undef);
$user_table->attach ($user_entry, 1, 2, 0, 1, "fill", 0, 0, 0);
$user_entry->show ();
}
$group_label = new Gtk::Label ("group: ");
$user_table->attach ($group_label, 0, 1, 1, 2, "fill", 0, 0, 0);
$group_label->show ();
$group_entry = new Gtk::Entry ( 10 );
$group_entry->set_usize (60, undef);
$user_table->attach ($group_entry, 1, 2, 1, 2, "fill", 0, 0, 0);
$group_entry->show ();
$separator1 = new Gtk::HSeparator ();
$main_vbox->pack_start ($separator1, $true, $true, 10);
$separator1->show ();
# Time for the chmod-section
$chmod_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);
$chmod_table = new Gtk::Table (5, 7, $true);
$chmod_table_alignment->add ($chmod_table);
$main_vbox->pack_start ($chmod_table_alignment, $false, $false, 0);
$chmod_table->set_col_spacings ( 0 );
$chmod_table_alignment->show ();
$chmod_table->show ();
# Adding the labels to the chmod_table
$user_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);
$user_chmod_label = new Gtk::Label ("user:");
$user_chmod_label_alignment->add ($user_chmod_label);
$chmod_table->attach ($user_chmod_label_alignment, 0, 1, 2, 3,"fill", 0, 0, 0);
$user_chmod_label_alignment->show ();
$user_chmod_label->show ();
$group_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);
$group_chmod_label = new Gtk::Label ("group:");
$group_chmod_label_alignment->add ($group_chmod_label);
$chmod_table->attach ($group_chmod_label_alignment,0, 1, 3, 4,"fill", 0, 0, 0);
$group_chmod_label_alignment->show ();
$group_chmod_label->show ();
$others_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);
$others_chmod_label = new Gtk::Label ("others:");
$others_chmod_label_alignment->add ($others_chmod_label);
$chmod_table->attach ($others_chmod_label_alignment,0, 1, 4, 5,"fill", 0, 0, 0);
$others_chmod_label_alignment->show ();
$others_chmod_label->show ();
# Adding the labels and the buttons to the read_vbox
$read_label = new Gtk::Label ("read");
$chmod_table->attach ($read_label, 1, 3, 0, 1, 0, 0, 0, 0);
$read_label->show ();
$read_plus_label = new Gtk::Label ("+");
$chmod_table->attach ($read_plus_label, 1, 2, 1, 2, 0, 0, 0, 0);
$read_plus_label->show ();
$read_minus_label = new Gtk::Label ("-");
$chmod_table->attach ($read_minus_label, 2, 3, 1, 2, 0, 0, 0, 0);
$read_minus_label->show ();
$user_plus_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_plus_read_button, 1, 2, 2, 3, 0, 0, 0, 0);
$user_plus_read_button->show ();
$user_minus_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_minus_read_button, 2, 3, 2, 3, 0, 0, 0, 0);
$user_minus_read_button->show ();
#callbacks
$user_plus_read_button->signal_connect ("clicked", \&check_button_callback,
$user_minus_read_button);
$user_minus_read_button->signal_connect ("clicked", \&check_button_callback,
$user_plus_read_button);
$group_plus_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_plus_read_button, 1, 2, 3, 4, 0, 0, 0, 0);
$group_plus_read_button->show ();
$group_minus_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_minus_read_button, 2, 3, 3, 4, 0, 0, 0, 0);
$group_minus_read_button->show ();
#callbacks
$group_plus_read_button->signal_connect ("clicked", \&check_button_callback,
$group_minus_read_button);
$group_minus_read_button->signal_connect ("clicked", \&check_button_callback,
$group_plus_read_button);
$others_plus_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_plus_read_button, 1, 2, 4, 5, 0, 0, 0, 0);
$others_plus_read_button->show ();
$others_minus_read_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_minus_read_button, 2, 3, 4, 5, 0, 0, 0, 0);
$others_minus_read_button->show ();
#callbacks
$others_plus_read_button->signal_connect ("clicked", \&check_button_callback,
$others_minus_read_button);
$others_minus_read_button->signal_connect ("clicked", \&check_button_callback,
$others_plus_read_button);
# Adding the labels and the buttons to the write_vbox
$write_label = new Gtk::Label ("write");
$chmod_table->attach ($write_label, 3, 5, 0, 1, 0, 0, 0, 0);
$write_label->show ();
$write_plus_label = new Gtk::Label ("+");
$chmod_table->attach ($write_plus_label, 3, 4, 1, 2, 0, 0, 0, 0);
$write_plus_label->show ();
$write_minus_label = new Gtk::Label ("-");
$chmod_table->attach ($write_minus_label, 4, 5, 1, 2, 0, 0, 0, 0);
$write_minus_label->show ();
$user_plus_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_plus_write_button, 3, 4, 2, 3, 0, 0, 0, 0);
$user_plus_write_button->show ();
$user_minus_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_minus_write_button, 4, 5, 2, 3, 0, 0, 0, 0);
$user_minus_write_button->show ();
#callbacks
$user_plus_write_button->signal_connect ("clicked", \&check_button_callback,
$user_minus_write_button);
$user_minus_write_button->signal_connect ("clicked", \&check_button_callback,
$user_plus_write_button);
$group_plus_read_button = new Gtk::CheckButton ();
$group_plus_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_plus_write_button, 3, 4, 3, 4, 0, 0, 0, 0);
$group_plus_write_button->show ();
$group_minus_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_minus_write_button, 4, 5, 3, 4, 0, 0, 0, 0);
$group_minus_write_button->show ();
#callbacks
$group_plus_write_button->signal_connect ("clicked", \&check_button_callback,
$group_minus_write_button);
$group_minus_write_button->signal_connect ("clicked", \&check_button_callback,
$group_plus_write_button);
$others_plus_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_plus_write_button, 3, 4, 4, 5, 0, 0, 0, 0);
$others_plus_write_button->show ();
$others_minus_write_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_minus_write_button, 4, 5, 4, 5, 0, 0, 0, 0);
$others_minus_write_button->show ();
#callbacks
$others_plus_write_button->signal_connect ("clicked", \&check_button_callback,
$others_minus_write_button);
$others_minus_write_button->signal_connect ("clicked", \&check_button_callback,
$others_plus_write_button);
# Adding the labels and the buttons to the execute_vbox
$execute_label = new Gtk::Label ("execute");
$chmod_table->attach ($execute_label, 5, 7, 0, 1, 0, 0, 0, 0);
$execute_label->show ();
$execute_plus_label = new Gtk::Label ("+");
$chmod_table->attach ($execute_plus_label, 5, 6, 1, 2, 0, 0, 0, 0);
$execute_plus_label->show ();
$execute_minus_label = new Gtk::Label ("-");
$chmod_table->attach ($execute_minus_label, 6, 7, 1, 2, 0, 0, 0, 0);
$execute_minus_label->show ();
$user_plus_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_plus_execute_button, 5, 6, 2, 3, 0, 0, 0, 0);
$user_plus_execute_button->show ();
$user_minus_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($user_minus_execute_button, 6, 7, 2, 3, 0, 0, 0, 0);
$user_minus_execute_button->show ();
#callbacks
$user_plus_execute_button->signal_connect ("clicked", \&check_button_callback,
$user_minus_execute_button);
$user_minus_execute_button->signal_connect ("clicked", \&check_button_callback,
$user_plus_execute_button);
$group_plus_read_button = new Gtk::CheckButton ();
$group_plus_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_plus_execute_button, 5, 6, 3, 4, 0, 0, 0, 0);
$group_plus_execute_button->show ();
$group_minus_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($group_minus_execute_button, 6, 7, 3, 4, 0, 0, 0, 0);
$group_minus_execute_button->show ();
#callbacks
$group_plus_execute_button->signal_connect ("clicked", \&check_button_callback,
$group_minus_execute_button);
$group_minus_execute_button->signal_connect ("clicked", \&check_button_callback,
$group_plus_execute_button);
$others_plus_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_plus_execute_button, 5, 6, 4, 5, 0, 0, 0, 0);
$others_plus_execute_button->show ();
$others_minus_execute_button = new Gtk::CheckButton ();
$chmod_table->attach ($others_minus_execute_button, 6, 7, 4, 5, 0, 0, 0, 0);
$others_minus_execute_button->show ();
#callbacks
$others_plus_execute_button->signal_connect ("clicked", \&check_button_callback,
$others_minus_execute_button);
$others_minus_execute_button->signal_connect ("clicked",\&check_button_callback,
$others_plus_execute_button);
$separator2 = new Gtk::HSeparator ();
$main_vbox->pack_start ($separator2, $true, $true, 10);
$separator2->show ();
# Creating the list with filenames and permissions
$file_info_hbox_alignment = new Gtk::Alignment (0.5,0,0,0);
$file_info_hbox = new Gtk::HBox ($false, 0);
$file_info_hbox_alignment->add ($file_info_hbox);
$main_vbox->pack_start ($file_info_hbox_alignment, $false, $false, 0);
$file_info_hbox_alignment->show ();
$file_info_hbox->show ();
$permission_vbox = new Gtk::VBox ($fase, 0);
$file_info_hbox->pack_start ($permission_vbox, $false, $false, 20);
$permission_vbox->show ();
$owner_vbox = new Gtk::VBox ($false, 0);
$file_info_hbox->pack_start ($owner_vbox, $false, $false, 10);
$owner_vbox->show ();
$group_vbox = new Gtk::VBox ($false, 0);
$file_info_hbox->pack_start ($group_vbox, $false, $false, 10);
$group_vbox->show ();
$filename_vbox = new Gtk::VBox ($false, 0);
$file_info_hbox->pack_start ($filename_vbox, $false, $false, 20);
$filename_vbox->show ();
$i = 0;
foreach ( @ARGV ) {
$file_info = `ls -ld \"$_\"`;
chop $file_info;
$rights = $file_info;
$rights =~ s/\s.*//;
$owner = $file_info;
$owner =~ s/\S+\s+\S+\s+//;
$owner =~ s/\s.*//;
$group = $file_info;
$group =~ s/\S+\s+\S+\s+\S+\s+//;
$group =~ s/\s.*//;
$name = $file_info;
$name =~ s/\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+//;
$permissions[$i] = new Gtk::Label ("$rights");
$permission_vbox->pack_start ($permissions[$i], $false, $false, 0);
$permissions[$i]->show ();
$owners_alignment[$i] = new Gtk::Alignment (0,1,0,0);
$owners[$i] = new Gtk::Label ("$owner");
$owners_alignment[$i]->add ($owners[$i]);
$owner_vbox->pack_start ($owners_alignment[$i],$false, $false, 0);
$owners_alignment[$i]->show ();
$owners[$i]->show ();
$groups_alignment[$i] = new Gtk::Alignment (0,1,0,0);
$groups[$i] = new Gtk::Label ("$group");
$groups_alignment[$i]->add ($groups[$i]);
$group_vbox->pack_start ($groups_alignment[$i],$false, $false, 0);
$groups_alignment[$i]->show ();
$groups[$i]->show ();
$filenames_alignment[$i] = new Gtk::Alignment (0,1,0,0);
$filenames[$i] = new Gtk::Label ("$name");
$filenames_alignment[$i]->add ($filenames[$i]);
$filename_vbox->pack_start ($filenames_alignment[$i],$false, $false, 0);
$filenames_alignment[$i]->show ();
$filenames[$i]->show ();
$i++;
}
$separator3 = new Gtk::HSeparator ();
$main_vbox->pack_start ($separator3, $true, $true, 10);
$separator3->show ();
#This is the last line of widgets in the program...
$last_hbox = new Gtk::HBox ( $false, 0);
$main_vbox->pack_start ($last_hbox, $false, $false, 5);
$last_hbox->show ();
$recursive_button = new Gtk::CheckButton ("Change recursive");
$last_hbox->pack_start ($recursive_button, $false, $false, 10);
$recursive_button->show ();
$ok_button = new Gtk::Button ("Ok");
$last_hbox->pack_start ($ok_button, $false, $false, 10);
$ok_button->signal_connect ('clicked', \&chmod);
$ok_button->show;
$cancel_button = new Gtk::Button ("Cancel");
$last_hbox->pack_start ($cancel_button, $false, $false, 10);
$cancel_button->signal_connect ('clicked', sub { Gtk->exit (0) } );
$cancel_button->show ();
$window->show ();
main Gtk;
exit (1);
sub check_button_callback
{
$button1 = $_[0];
$button2 = $_[1];
$button2->set_active ($false) if $button1->get_active;
}
sub chmod
{
my $mode = 0;
my $recursive = "";
my $files = "";
my $new_group = $group_entry->get_text ();
my $upmode = "u+";
my $ummode = "u-";
my $gpmode = "g+";
my $gmmode = "g-";
my $opmode = "o+";
my $ommode = "o-";
$upmode .= "r" if $user_plus_read_button->active;
$upmode .= "w" if $user_plus_write_button->active;
$upmode .= "x" if $user_plus_execute_button->active;
$ummode .= "r" if $user_minus_read_button->active;
$ummode .= "w" if $user_minus_write_button->active;
$ummode .= "x" if $user_minus_execute_button->active;
$gpmode .= "r" if $group_plus_read_button->active;
$gpmode .= "w" if $group_plus_write_button->active;
$gpmode .= "x" if $group_plus_execute_button->active;
$gmmode .= "r" if $group_minus_read_button->active;
$gmmode .= "w" if $group_minus_write_button->active;
$gmmode .= "x" if $group_minus_execute_button->active;
$opmode .= "r" if $others_plus_read_button->active;
$opmode .= "w" if $others_plus_write_button->active;
$opmode .= "x" if $others_plus_execute_button->active;
$ommode .= "r" if $others_minus_read_button->active;
$ommode .= "w" if $others_minus_write_button->active;
$ommode .= "x" if $others_minus_execute_button->active;
$recursive = "-R" if $recursive_button->active;
$recursive = "-R" if $recursive_button->active;
$upmode = "" if $umode =~ /^u\+$/;
$ummode = "" if $umode =~ /^u\-$/;
$gpmode = "" if $gmode =~ /^g\+$/;
$gmmode = "" if $gmode =~ /^g\-$/;
$opmode = "" if $omode =~ /^o\+$/;
$ommode = "" if $omode =~ /^o\-$/;
foreach (@ARGV) {
$files .= "\"$_\"" . " ";
}
system ("chmod $recursive $upmode,$gpmode,$opmode,$ummode,$gmmode,$ommode $files");
if ($user eq "root") {
my $new_user = $user_entry->get_text ();
system ("chown $recursive $new_user $files") if $new_user =~ /\w+/;
}
system ("chgrp $recursive $new_group $files") if $new_group =~ /\w+/;
Gtk->exit ( 0 );
}
==== nautilus-scripts/Varios/FileSystemManagement/copyhome ====
$ cat nautilus-scripts/Varios/FileSystemManagement/copyhome
#!/bin/sh
# copyhome: copies the selected file(s) to home directory
# (if able)
for arg
do
if [ -f ~/"$arg" ]; then
MSG="File: '$arg' already exists in home directory. Overwrite?"
if
gdialog --title "Overwrite?" --defaultno --yesno "$MSG" 200 100
then
cp "$arg" ~/"$arg"
fi
else
cp "$arg" ~/"$arg"
fi
done
==== nautilus-scripts/Varios/FileSystemManagement/Get_Photos ====
$ cat nautilus-scripts/Varios/FileSystemManagement/Get_Photos
#!/usr/bin/perl -w
# Created: Wed Dec 26 19:46:59 2001
# Last modified: Wed Dec 26 20:35:47 2001
# Time-stamp: <01/12/26 20:35:47 nevin>
## Copyright (C) 2001 by Nevin Kapur
## Author: Nevin Kapur
## This is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2, or (at your option)
## any later version.
## This is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
## Get photos from a digital camera. This script is meant to be run on
## a selected directory. It will silently fail till I get around to
## playing with gdialog.
## How to run gphoto; By default, this script will transfer everything
## on the default camera to the first selected directory. (I haven't
## experimented with what Nautilus thinks is the "first" directory if
## more that one directory is selected.)
my $GPHOTO = q[/usr/bin/gphoto2];
my @GPHOTO_OPTIONS = qw[ -q -P ];
## It is a shame that the scripts menu does not become active unless
## something is selected, otherwise we could have a version where the
## images would be magically appear in the current directory;
## It would be nice if one could assume the existence of these
## modules, but they are not bundled with Perl
## use URI;
## use URI::Escape;
## Silently discard the output if more that one directory is selected
my $uri = (split "\n", $ENV{NAUTILUS_SCRIPT_SELECTED_URIS})[0];
## Hack, hack, hack;
$uri =~ s[^file://][];
## From the URI::Escape man page:
$uri =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
## Only execute if what we got was a directory
if (-d $uri) {
chdir $uri or die;
system $GPHOTO, @GPHOTO_OPTIONS;
}
__END__
==== nautilus-scripts/Varios/FileSystemManagement/junksorter ====
$ cat nautilus-scripts/Varios/FileSystemManagement/junksorter
#!/bin/bash
################################################################################
## Script: junksorter
## Author: Unknown
## Date: Unknown
## Category: File Utilities
################################################################################
## Description: This script will automatically sort files for you, into whatever
## directories you want, under a root-level 'junk'directory. For
## seamless integration, make this ~/.junk and symlink directories
## in there. Includes detection of mp3s (requires mp3info), images,
## movies, text and pdf documents, and various other stuff.
################################################################################
## Changes
## Author: Brian Pepple
## 09.06.2003 Modified mp3 section, and various clean-up.
##
## Author: Vittorio Colao
## 26.12.2003 Added mp3 detection.
## 04.02.2004 Made it working under nautilus-2.x
################################################################################
## The home directory may need to be changed to a hard-coded path.
junk= ~/junk
msg="already exists in"
overwrite="Overwrite?"
file="File: "
for arg in $(echo $NAUTILUS_SCRIPT_SELECTED_URIS|sed 's/file:\/\///');
do
artist="misc"
album="."
new_artist=""
new_album=""
filename="$arg"
filetype=`file -b "$filename"`
if [ -n "`echo $filetype | grep -i 'image' `" ]; then
dest="$junk/images/"
elif [ -n "`echo $filetype | grep -i 'rpm' `" ]; then
dest="$junk/rpms/"
elif [ -n "`echo $filename | grep -i 'svg' `" ]; then
dest="$junk/images/"
elif [ -n "`echo $filetype | grep -i 'audio' `" ]; then
dest="$junk/audio/"
elif [ -n "`echo $filename | grep -i 'MPG' `" ]; then
dest="$junk/video/"
elif [ -n "`echo $filetype | grep -i 'MPEG' `" ]; then
dest="$junk/video/"
elif [ -n "`echo $filetype | grep -i 'AVI' `" ]; then
dest="$junk/video/"
elif [ -n "`echo $filetype | grep -i 'pdf' `" ]; then
dest="$junk/documents/"
elif [ -n "`echo $filetype | grep -i 'PostScript' `" ]; then
dest="$junk/documents/"
elif [ -n "`echo $filetype | grep -i 'Microsoft Office Document' `" ];
then
dest="$junk/documents/"
elif [ -n "`echo $filetype | grep -i 'Rich Text Format' `" ]; then
dest="$junk/documents/"
elif [ -n "`echo $filetype | grep 'TeX' `" ]; then
dest="$junk/documents/"
elif [ -n "`echo $filename | grep 'TeX' `" ]; then
dest="$junk/documents/"
elif [ -n "`echo $filetype | grep -i 'zip' `" ]; then
dest="$junk/archives/"
elif [ -n "`echo $filetype | grep -i 'script'`" ]; then
dest="$junk/text/scripts/"
elif [ -n "`echo $filetype | grep -i 'text' `" ]; then
dest="$junk/text/"
elif [ -n "`echo $filetype | grep -i 'MP3' `" ]; then
new_artist="`mp3info -p "%a" "$filename"`"
new_album="`mp3info -p "%l" "$filename"`"
if [ ! -d "$junk/mp3" ]; then
mkdir -p "$junk/mp3"
fi
if [ -n "$new_artist" ]; then
artist="$new_artist"
if [ ! -d "$junk/mp3/$artist" ]; then
mkdir -p "$junk/mp3/$artist"
fi
fi
if [ -n "$new_album" ]; then
album="$new_album"
if [ ! -d "$junk/mp3/$artist/$album" ]; then
mkdir -p "$junk/mp3/$artist/$album"
fi
fi
dest="$junk/mp3/$artist/$album/"
else
dest="$junk/misc/"
fi
#Now, create the destination directory if it doesn't exist
if [ ! -d $dest ]; then
mkdir -p "$dest"
fi
#Finally, move the file to the destination (if it doesn't exist there)
if [ -f "$dest$filename" ]; then
if gdialog --title "Overwrite?" --defaultno --yesno "$file
$filename $msg $dest $overwrite" 4 100; then
mv "$filename" "$dest"
fi
else
mv "$filename" "$dest"
fi
done
==== nautilus-scripts/Varios/FileSystemManagement/Junksorter.pl ====
$ cat nautilus-scripts/Varios/FileSystemManagement/Junksorter.pl
#!/usr/bin/perl -w
#########################################################################################
# Nautilus script for sorting home directory files.
#########################################################################################
#
# NAME: junksorter.pl
#
# AUTHOR: Brian Pepple
#
# DESCRIPTION: This script sorts the selected files based on the Mime
# information, and moves the file to the appropriate
# folder. It will also sort mp3's based on the information
# contained within their ID3 tag.
#
# REQUIREMENTS: Nautilus file manager
# Zenity, which replaces the venerable gdialog.
# Shared Mime Info-0.12 : available at
# http://freedesktop.org/Software/shared-mime-info
# Perl >= 5.8
# Perl Modules: MP3::Tag, File::Copy, File::MimeInfo
#
# INSTALLATION: GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory,
#
# USAGE: Select the files that you would like to sort in Nautilus,
# right click, go to Scripts, and then select this script.
# IF the file being moved would overwrite an existing file,
# a dialog window will appear giving you the option to cancel
# the action for that file.
#
# VERSION INFO: 0.8 (20031224) - Merged some switch cases, to reduce
# number of switches needed, and speed
# up script.
# 0.7 (20031220) - Cleaned up switch statement.
# 0.6 (20031216) - Use enviroments $HOME value, instead of
# hard-coding the path.
# 0.5 (20031212) - Added hack that will allow files on the
# users desktop to be handled correctly.
# If a directory is accidently selected the
# script will not move it.
# 0.4 (20031129) - Changed base location to default home,
# this will make it play better with the
# spatial version of Nautilus, that is in
# Gnome >= 2.5.0. Also, added some error
# checking.
# 0.3 (20031128) - Replaced folder creation loop, and some
# minor clean up.
# 0.2 (20031127) - Added quick hack to add base folder. Will
# clean this in later version.
# 0.1 (20031126) - Initial public release
#
# COPYRIGHT: Copyright (C) 2003 Brian Pepple
#
# LICENSE: GNU GPL
#
#########################################################################################
use MP3::Tag;
use File::Basename qw(basename);
use File::Copy qw(move);
use File::MimeInfo qw(mimetype);
use Switch;
use strict;
$|++; # Turn on autoflush
#########################################################################################
## EDIT THIS to suit your needs.
##
## Directory paths.
my $home = $ENV{'HOME'};
my $rpm = $home . '/rpms/';
my $deb = $home . '/debs/';
my $video = $home . '/video/';
my $iso = $home . '/iso/';
my $image = $home . '/images/';
my $document = $home . '/documents/'; # If you are using Ximian
# change to 'Documents'
my $spreadsheet = $document . 'spreadsheets/';
my $webpage = $document . 'web/';
my $script = $document . 'scripts/';
my $template = $document . 'templates/';
my $font = $home . '/fonts/';
my $music = $home . '/music/';
my $archive = $home . '/archives/';
#########################################################################################
sub makedir {
my $directory = (shift or "");
# If directory already exist stop subroutine.
return if -d $directory;
mkdir $directory, 0700
or die "Problem creating directory $directory: $!\n";
}
sub taginfo {
my $artist;
my $album;
my $temppath;
# Create path information from ID3 tag.
my $mp3 = MP3::Tag->new(@_);
$mp3->get_tags;
if (exists $mp3->{ID3v1}) {
my $id3v1 = $mp3->{ID3v1};
$artist = $id3v1->artist;
$album = $id3v1->album;
$temppath = $music . "$artist/$album/";
} elsif (exists $mp3->{ID3v2}) {
my $id3v2 = $mp3->{ID3v2};
$artist = $id3v2->artist;
$album = $id3v2->album;
$temppath = $music . "$artist/$album/";
} else {
$artist = "misc";
$temppath = $music . "$artist/";
}
$mp3->close();
# Create folders for music files.
my @folders = ($music, $music . $artist, $temppath);
foreach (@folders) {
unless (-d ($_)) {
makedir ($_);
}
}
return $temppath;
}
#########################################################################################
## MAIN LOGIC
#########################################################################################
# If no file selected tell the user, and stop the script.
if (!@ARGV) {
system "zenity", "--info", "--title", "No Files Selected", "--text",
"Unable to run junksorter.pl No files were selected.";
exit;
}
foreach (@ARGV) {
# Starting variables.
my $file;
my $dir = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'};
my $base = basename ($_);
my $mime = mimetype($_);
my $dest;
#system "zenity", "--info", "--title", "Debug", "--text",
#"Dir: $dir\nBase: $base\nMime: $mime";
#exit;
# Ugly hack to determine if the script is being ran from the Desktop.
if ($dir =~ /x-nautilus-desktop/) {
$file = $home . "/Desktop/" . $base;
} else {
if ($dir =~ /file:\/\/\//) {
$dir =~ s/file:\/\///;
$file = $dir . '/' . $base;
} else {
system "zenity", "--info", "--title", "Error", "--text",
"Unable to move selected file. $dir is not a valid path.";
exit;
}
}
# Start of switch statement, which determines the file type,
# and determines where file should be moved. If type isn't here,
# the file is move to $home/misc/ folder.
switch ($mime) {
case /video/ {$dest = $video}
case /image/ {$dest = $image}
case /audio/ {$dest = &taginfo($file)}
case /perl/ {$dest = $script; &makedir($document)}
case /x-python/ {$dest = $script; &makedir($document)}
case /x-ruby/ {$dest = $script; &makedir($document)}
case /x-shellscript/ {$dest = $script; &makedir($document)}
case /x-tar/ {$dest = $archive}
case /x-gtar/ {$dest = $archive}
case /x-bzip/ {$dest = $archive}
case /x-bzip-compressed-tar/ {$dest = $archive}
case /x-compress/ {$dest = $archive}
case /x-compressed-tar/ {$dest = $archive}
case /x-gzip/ {$dest = $archive}
case /zip/ {$dest = $archive}
case /word/ {$dest = $document}
case /pdf/ {$dest = $document}
case /pgp/ {$dest = $document}
case /postscript/ {$dest = $document}
case /rtf/ {$dest = $document}
case /ms-excel/ {$dest = $spreadsheet; &makedir($document)}
case /ms-powerpoint/ {$dest = $document}
case /ms-word/ {$dest = $document}
case /html/ {$dest = $webpage; &makedir($document)}
case /x-php/ {$dest = $webpage; &makedir($document)}
case /css/ {$dest = $webpage; &makedir($document)}
case /calc/ {$dest = $spreadsheet; &makedir($document)}
case /draw/ {$dest = $spreadsheet; &makedir($document)}
case /template/ {$dest = $template; &makedir($document)}
case /impress/ {$dest = $document}
case /math/ {$dest = $spreadsheet; &makedir($document)}
case /writer/ {$dest = $document}
case /x-amipro/ {$dest = $document}
case /stardivision.chart/ {$dest = $document}
case /stardivision.mail/ {$dest = $document}
case /x-asp/ {$dest = $webpage; &makedir($document)}
case /x-cd-image/ {$dest = $iso}
case /x-cgi/ {$dest = $webpage; &makedir($document)}
case /x-dia-diagram/ {$dest = $document}
case /font/ {$dest = $font}
case /x-gnumeric/ {$dest = $spreadsheet; &makedir($document)}
case /x-jar/ {$dest = $archive}
case /x-rpm/ {$dest = $rpm}
case /x-deb/ {$dest = $deb}
case /x-mswrite/ {$dest = $document}
case /x-rar/ {$dest = $archive}
else {$dest = $home . '/misc/'}
}
# Create folders if they don't already exist.
my @global_folders = ($dest);
foreach (@global_folders) {
unless (-d ($_)) {
makedir ($_);
}
}
# Move the select files to appropriate folder,
# ignoring any folders accidently selected.
unless (-d $file) {
if (-e $dest . $base) {
# Ask the user if he wishes to overwrite file that already exists.
my $overwrite = system "zenity", "--question", "--title",
"File Exists", "--text",
"$base already exists in $dest. Do you want to overwrite it?";
# Zenity --question will return 0 when the user presses OK.
if ($overwrite == 0) {
move ($file, $dest . $base);
}
} else {
move ($file, $dest . $base);
}
}
}
==== nautilus-scripts/Varios/FileSystemManagement/linker ====
$ cat nautilus-scripts/Varios/FileSystemManagement/linker
#!/bin/sh
#Linker...Creates a link into your home directory
# With thanks to Doug Nordwall
for arg
do
ln -s $PWD/$arg ~/$arg
done
==== nautilus-scripts/Varios/FileSystemManagement/lowercase ====
$ cat nautilus-scripts/Varios/FileSystemManagement/lowercase
#!/bin/sh
# lowercase: Changes input to lowercase.
for arg
do
tmp=`echo "$arg" | tr '[A-Z]' '[a-z]'`
if [ -f $tmp ]
then
msg="Lowercase filename: '$tmp' already exists."
gdialog --msgbox "$msg" 100 100
else
mv "$arg" "$tmp"
fi
done
==== nautilus-scripts/Varios/FileSystemManagement/Make_Link ====
$ cat nautilus-scripts/Varios/FileSystemManagement/Make_Link
#!/bin/sh
#
# Nautilus script that links selected files to desktop.
#
# Author: Krzysztof Luks
#
# Copyright (C) 2002 Krzysztof Luks
# Licence: GNU GPL
#
# Dependency: nautilus and ln ;)
#
DESKTOP="$HOME/.gnome-desktop"
# We don't want to split NAUTILUS_SCRIPT_SELECTED_FILE_PATHS on spaces.
IFS="
"
for FILE in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
do
if [ ! -e "$DESKTOP/`basename $FILE`" ]
then
ln -s "$FILE" $DESKTOP
fi
done
==== nautilus-scripts/Varios/FileSystemManagement/mount_loopback ====
$ cat nautilus-scripts/Varios/FileSystemManagement/mount_loopback
#!/bin/sh
# Name: (Un)Mount Loopback
# Description: Allows for mounting and unmounting of loopback filesystems
# Author: Caleb Shay
# License: GPL
# This script makes several assumptions:
# 1. You have gdialog installed in your path
# 2. You have xsu installed in your path
# 3. You have loopback device support in your kernel
# 4. You have the mountpints /mnt/loop0 - /mnt/loop7
# 5. You have your kernel compiled with the default number (8) of loopback devices
# 6. Your loopback files will either be iso9660 cdroms or efs filesystems
# (but adding more filesystems is trivial)
for arg
do
skipFile=0;
ftype=$(file "${arg}");
if [ "`df | grep \"${arg}\"`" ]; then
xsu -u root -t "Unmount Loopback Filesystem" -d -e -- umount \"${arg}\";
continue;
fi;
case "$ftype" in
*ISO\ 9660\ CD-ROM\ filesystem*)
mtype="iso9660";
;;
*SGI\ disk\ label*)
mtype="efs";
;;
*)
gdialog --msgbox "Don't know how to mount\n${ftype}" 300 400;
skipFile=1;
;;
esac;
if [ ${skipFile} -lt 1 ]; then
mounted=0;
for loop in loop0 loop1 loop2 loop3 loop4 loop5 loop6 loop7; do
if [ "`df | grep /mnt/${loop}`" ]; then
echo "Something already mounted on ${loop}";
else
mounted=1;
xsu -u root -t "Mount Loopback Filesystem" -d -e -- mount -o loop -t ${mtype} \"${arg}\" /mnt/${loop};
nautilus /mnt/${loop}
break;
fi;
done;
if [ ${mounted} -lt 1 ]; then
gdialog --msgbox "No available mount points for ${arg}" 300 200;
fi
fi;
done
==== nautilus-scripts/Varios/FileSystemManagement/moveup ====
$ cat nautilus-scripts/Varios/FileSystemManagement/moveup
#!/bin/sh
# moveup: moves the selected file(s) to parent directory
# (if able)
for arg
do
if [ -f ../"$arg" ]
then
MSG="Filename: '$arg' already exists in parent directory."
if
gdialog --title "Overwrite?" --defaultno --yesno "$MSG" 200 100
then
mv "$arg" ../"$arg"
fi
else
mv "$arg" ../"$arg"
fi
done
==== nautilus-scripts/Varios/FileSystemManagement/QuickBurn ====
$ cat nautilus-scripts/Varios/FileSystemManagement/QuickBurn
#!/usr/bin/env python2
# Nautilus CD burning script
#
# Owner: Michele Campeotto
# http://www.micampe.it
#
# Licence: GNU GPL
# Copyright (C) 2002 Michele Campeotto
#
# Dependency: GTK+ >= 2.0
# PyGTK >= 1.99.8
# Python >= 2.2
# mkisofs and cdrecord
#
# 20020330 - Ver 0.1
# First release
import sys, os, os.path, popen2
import gtk
# To configure the script, you should only need to edit these values
device = '0,0,0'
driver = 'mmc_cdr'
options = 'driveropts=burnproof'
dummy = '-dummy'
# To actually burn CDs, uncomment the following line and comment out the next one
#burn_command_template = 'mkisofs -gui -r -J -l -D -L -graft-points %(graft_points)s | cdrecord dev="%(device)s" %(options)s driver=%(driver)s %(dummy)s -eject -pad -tsize=%(size)ss -'
burn_command_template = 'mkisofs -gui -r -J -l -D -L -o image.img -graft-points %(graft_points)s'
size_command_template = 'mkisofs -r -J -l -D -L -v -print-size -graft-points %(graft_points)s'
def build_mappings(paths):
mappings = []
for i in paths:
if os.path.isdir(i):
mappings.append('"%s/=%s"' % (i.split('/')[-1], i))
else:
mappings.append('"%s=%s"' % (i.split('/')[-1], i))
return mappings
def burn_command(paths):
global graft_points
graft_points = ' '.join(build_mappings(paths))
return burn_command_template % globals()
def size_command(paths):
global graft_points
graft_points = ' '.join(build_mappings(paths))
return size_command_template % globals()
def get_image_size(paths):
return int(os.popen4(size_command(paths))[1].readlines()[-1])
def burn(paths, progress):
def cb(fd, cond):
data = os.read(fd, 80)
print data,
if data.find('extents') >= 0:
progress.set_fraction(1.0)
progress.set_text('100%')
return gtk.TRUE
elif data.find('read/written') >= 0:
progress.set_text('Finishing...')
try:
perc = int(data.split('.')[0])
progress.set_fraction(perc/100.0)
progress.set_text('%d%%' % (perc,))
except (ValueError):
pass
command = burn_command(paths)
print command
pipe = popen2.Popen4(command)
gtk.input_add(pipe.fromchild, gtk.gdk.INPUT_READ, cb)
while pipe.poll() < 0:
gtk.mainiteration()
return pipe.poll()
def response(dialog, response):
sys.exit()
def burn_window(paths):
win = gtk.Dialog("Nautilus Quick Burner", None, gtk.DIALOG_MODAL,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
win.connect('response', response)
win.set_default_size(400, -1)
hbox = gtk.HBox()
hbox.set_border_width(8)
hbox.set_spacing(8)
win.vbox.pack_start(hbox)
stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_INFO,
gtk.ICON_SIZE_DIALOG)
hbox.pack_start(stock, gtk.FALSE, gtk.FALSE)
vbox = gtk.VBox()
vbox.set_spacing(8)
hbox.pack_start(vbox, gtk.TRUE, gtk.TRUE)
label = gtk.Label("Burning...")
label.set_use_markup(gtk.TRUE)
label.set_alignment(0, 0.5)
vbox.pack_start(label)
label = gtk.Label('\n'.join(paths))
label.set_alignment(0, 0.5)
vbox.pack_start(label)
win.progress = gtk.ProgressBar()
win.progress.set_fraction(0.0)
win.progress.set_text("Initializing...")
vbox.pack_start(win.progress)
win.show_all()
return win
def help():
win = gtk.Dialog("Nautilus Quick Burner", None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
hbox = gtk.HBox(gtk.FALSE, 8)
hbox.set_border_width(8)
win.vbox.pack_start(hbox)
stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR,
gtk.ICON_SIZE_DIALOG)
hbox.pack_start(stock)
label = gtk.Label("You must specify the files to be burned.")
hbox.pack_start(label)
win.show_all()
return win
def confirm(paths):
win = gtk.Dialog("Nautilus Quick Burner", None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
"_Burn 'em!", gtk.RESPONSE_OK))
hbox = gtk.HBox(gtk.FALSE, 8)
hbox.set_border_width(8)
win.vbox.pack_start(hbox)
stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION,
gtk.ICON_SIZE_DIALOG)
hbox.pack_start(stock)
vbox = gtk.VBox()
vbox.set_spacing(8)
hbox.pack_start(vbox)
label = gtk.Label("Are you sure you want to burn these?")
label.set_use_markup(gtk.TRUE)
label.set_alignment(0, 0.5)
vbox.pack_start(label)
label = gtk.Label('\n'.join(paths))
label.set_alignment(0, 0.5)
vbox.pack_start(label)
win.show_all()
response = win.run()
win.destroy()
return response
def error(paths):
win = gtk.Dialog("Burning finished", None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
hbox = gtk.HBox(gtk.FALSE, 8)
hbox.set_border_width(8)
win.vbox.pack_start(hbox)
stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR,
gtk.ICON_SIZE_DIALOG)
hbox.pack_start(stock)
vbox = gtk.VBox()
vbox.set_spacing(8)
hbox.pack_start(vbox)
label = gtk.Label("Some error occurred while building the image.")
label.set_use_markup(gtk.TRUE)
label.set_alignment(0.0, 0.5)
vbox.pack_start(label)
label = gtk.Label("Run:\n%s\nfrom the commman line to see what went wrong."
% size_command(paths))
label.set_use_markup(gtk.TRUE)
label.set_selectable(gtk.TRUE)
label.set_line_wrap(gtk.TRUE)
vbox.pack_start(label)
win.show_all()
response = win.run()
win.destroy()
return response
def success():
win = gtk.Dialog("Burning finished", None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
hbox = gtk.HBox(gtk.FALSE, 8)
hbox.set_border_width(8)
win.vbox.pack_start(hbox)
stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_INFO,
gtk.ICON_SIZE_DIALOG)
hbox.pack_start(stock)
label = gtk.Label("Burning process successfully completed.")
hbox.pack_start(label)
win.show_all()
response = win.run()
win.destroy()
return response
def failed():
win = gtk.Dialog("Burning failed", None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK))
hbox = gtk.HBox(gtk.FALSE, 8)
hbox.set_border_width(8)
win.vbox.pack_start(hbox)
stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_WARNING,
gtk.ICON_SIZE_DIALOG)
hbox.pack_start(stock)
label = gtk.Label("Burning process failed.")
hbox.pack_start(label)
win.show_all()
response = win.run()
win.destroy()
return response
def main():
global size
if len(sys.argv) == 1:
help().run()
else:
paths = [os.path.abspath(i) for i in sys.argv[1:]]
if confirm(paths) == gtk.RESPONSE_OK:
try:
size = get_image_size(paths)
except ValueError:
error(paths)
else:
win = burn_window(paths)
result = burn(paths, win.progress)
print result
win.destroy()
if result == 0:
success()
else:
failed()
if __name__ == '__main__':
main()
==== nautilus-scripts/Varios/FileSystemManagement/Search_Here ====
$ cat nautilus-scripts/Varios/FileSystemManagement/Search_Here
#!/bin/sh
# From Johnathan Bailes
# This script opens a gnome-search-tool in the directory you select.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Install in your ~/Nautilus/scripts directory.
# You need to be running Nautilus 1.0.3+ to use scripts.
cd $NAUTILUS_SCRIPT_CURRENT_URI
exec gnome-search-tool
==== nautilus-scripts/Varios/FileSystemManagement/set_exec ====
$ cat nautilus-scripts/Varios/FileSystemManagement/set_exec
#!/bin/sh
# set_exec
# Sets selected files as executable
# looping required for multiple filenames with spaces
for arg
do
chmod u+x "$arg"
done
==== nautilus-scripts/Varios/FileSystemManagement/set_read_only ====
$ cat nautilus-scripts/Varios/FileSystemManagement/set_read_only
#!/bin/sh
# set_read_only
# Sets selected files as executable
# looping required for multiple filenames with spaces
for arg
do
chmod ugo-w "$arg"
done
==== nautilus-scripts/Varios/FileSystemManagement/shredder ====
$ cat nautilus-scripts/Varios/FileSystemManagement/shredder
#!/bin/bash
# "Shredder" secure file delete for Nautilus
# Distributed under the terms of GNU GPL version 2 or later
# Copyright (C) James Jones
#
# Dependency : gdialog (gnome-utils)
# \A0 : shred (Colin Plumb's)
#
# From shred's info file, wise words:
#
# Please note* that `shred' relies on a very important assumption:
# that the filesystem overwrites data in place. This is the traditional
# way to do things, but many modern filesystem designs do not satisfy
# this assumption.
#
# Exceptions exist, and are noted in shred's info manual.
# Type 'info shred' from a prompt to see the list.
SHRED_PATH=/usr/bin #Path to shred binary.
if dialog=`gdialog --title "$1" --yesno "Are you sure you want to shred
$1" 100 200 --defaultno`
then
$SHRED_PATH/shred -zu "$1"
fi
==== nautilus-scripts/Varios/FileSystemManagement/UnExec ====
$ cat nautilus-scripts/Varios/FileSystemManagement/UnExec
#!/bin/sh
#
# This script removes executable bit from all files (excluding directories!)
# recursively. Very useful when you copy files from MS Win partition or from a
# CD recorded on Windows.
#
# Author: Krzysztof Luks
#
# Copyright (C) 2002 Krzysztof Luks
# Licence: GNU GPL 2 or later.
#
# set desired mode here
MODE="644"
# We don't want to split NAUTILUS_SCRIPT_SELECTED_FILE_PATHS on spaces.
IFS="
"
for ARG in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
do
if [ -d "$ARG" ]
then
for FILE in `find "$ARG" -type f`
do
chmod -f $MODE "$FILE"
done
elif [ -f "$ARG" ]
then
chmod -f $MODE "$ARG"
fi
done
==== nautilus-scripts/Varios/FileSystemManagement/uppercase ====
$ cat nautilus-scripts/Varios/FileSystemManagement/uppercase
#!/bin/sh
# uppercase: Renames input file to uppercase.
for arg
do
tmp=`echo "$arg" | tr '[a-z]' '[A-Z]'`
if [ -f $tmp ]
then
msg="Uppercase filename: '$tmp' already exists."
gdialog --msgbox "$msg" 100 100
else
mv "$arg" "$tmp"
fi
done
==== nautilus-scripts/Varios/Multimedia/convert_to_jpeg ====
$ cat nautilus-scripts/Varios/Multimedia/convert_to_jpeg
#!/bin/bash
while [ $# -gt 0 ]; do
picture=$1
jpg_file=`echo "$picture" | sed 's/\.\w*$/.jpg/'`
/usr/bin/convert -quality 75 "$picture" jpeg:"$jpg_file"
shift
done
==== nautilus-scripts/Varios/Multimedia/convert_to_png ====
$ cat nautilus-scripts/Varios/Multimedia/convert_to_png
#!/bin/bash
while [ $# -gt 0 ]; do
picture=$1
png_file=`echo "$picture" | sed 's/\.\w*$/.png/'`
/usr/bin/convert "$picture" png:"$png_file"
shift
done
==== nautilus-scripts/Varios/Multimedia/Create_Thumbnail ====
$ cat nautilus-scripts/Varios/Multimedia/Create_Thumbnail
#!/bin/bash
#
# Nautilus script -> Create big Thumbnails (upto 200x200) for selected files
#
# Owner : Hans-Bernhard Tr\FCtken
# hb.truetken@htp-tel.de
#
# Licence : GNU GPL
#
# Ver :1.0 Date 06.03.2002
#
# angelehnt an: http://www-user.tu-chemnitz.de/~kbo/linux/shellskript/conv.htm
#
# Dependency : ImageMagick, GNU shell utilities
for Datei in $*
do
if [ -f $Datei ]
then
echo "Bearbeite Datei $Datei ..."
DateiName=`basename $Datei`
DirName=`dirname $Datei`/.thumbnails
convert -geometry 200x200 $Datei $DirName/$DateiName.png
fi
done
exit 0
==== nautilus-scripts/Varios/Multimedia/create-vcd ====
$ cat nautilus-scripts/Varios/Multimedia/create-vcd
#!/bin/sh
#
# You can select multiple mpegs in Nautilus and and create a VCD CD image in bin/cue format.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Keith Conger
#
# This script is for use with Nautilus 1.0.3 + and GNU VCDImager 0.7.x +.
VCDIMGR_PATH=/usr/local/bin #Path to vcdimager binary
LABEL=$(gdialog --title "VCD Volume Label?" --inputbox "Volume Label.." 200 450 VCD 2>&1)
DIR=$(gdialog --title "VCD Image Directory?" --inputbox "Directory Location..." 200 450 ~/tmp/$1 2>&1)
mkdir $DIR
vcdimager --iso-volume-label=$LABEL --bin-file=$DIR/$1.bin --cue-file=$DIR/$1.cue $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> $DIR/$1.log
gdialog --separate-output --title "VCD Imager log" --textbox $DIR/$1.log 50 70 2>&1
rm $DIR/$1.log
==== nautilus-scripts/Varios/Multimedia/dv_to_mpg ====
$ cat nautilus-scripts/Varios/Multimedia/dv_to_mpg
#!/bin/bash
#
# You can select DV type2 stream and convert it into a vcd compliant
# mpeg.
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Keith Conger
#
# This script is for use with Nautilus 1.0.3 + and mjpegtools(CVS).
# Optional: gnome-utils and Xdialog
# Set this to either Xdialog, gdialog or none.
DIALOG=Xdialog
#Directory for temporary files
TMP_DIR=~/tmp
if [ "$DIALOG" = "Xdialog" ]; then
OUT_FILE=$(Xdialog --fselect ~/tmp 0 0 2>&1)
(
echo "0";
lav2wav $1 |mp2enc -V -o $TMP_DIR/sound.mpg
echo "35";
lav2yuv $1|yuvscaler -O VCD|mpeg2enc -f 1 -r 16 -o $TMP_DIR/video.mpg
echo "90";
mplex -f 1 $TMP_DIR/sound.mpg $TMP_DIR/video.mpg -o $OUT_FILE
echo "100";
rm $TMP_DIR/sound.mpg $TMP_DIR/video.mpg
)|
Xdialog --title "Creating MPEG.." --gauge "Percent complete:" 8 30
elif [ "$DIALOG" = "gdialog" ]; then
DIR=$(gdialog --title "MPEG file directory" --inputbox "Directory Location..." 200 450 ~/tmp/$1 2>&1)
lav2wav $1 |mp2enc -V -o $TMP_DIR/sound.mpg
lav2yuv $1|yuvscaler -O VCD|mpeg2enc -f 1 -r 16 -o $TMP_DIR/video.mpg
mplex -f 1 $TMP_DIR/sound.mpg $TMP_DIR/video.mpg -o $DIR/$1.mpg
rm $TMP_DIR/sound.mpg $TMP_DIR/video.mpg
else
lav2wav $1 |mp2enc -V -o $TMP_DIR/sound.mpg
lav2yuv $1|yuvscaler -O VCD|mpeg2enc -f 1 -r 16 -o $TMP_DIR/video.mpg
mplex -f 1 $TMP_DIR/sound.mpg $TMP_DIR/video.mpg -o ./$1.mpg
rm $TMP_DIR/sound.mpg $TMP_DIR/video.mpg
fi
==== nautilus-scripts/Varios/Multimedia/mirror_jpg ====
$ cat nautilus-scripts/Varios/Multimedia/mirror_jpg
#!/usr/bin/perl -w
# created on Sept. 14 by Shane Mueller
# http://g-scripts.sourceforge.net
# Based on script of:
# Matt Doller
#
# some code is borrowed from a script i found on tigert's web site
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
use Gtk;
use strict;
set_locale Gtk;
init Gtk;
my $false = 0;
my $true = 1;
my $window;
my $box1;
my $box2;
my $label;
my $pbar;
my $button;
my $separator;
my $file;
my $filenum;
my $random_file;
# Create the window
$window = new Gtk::Window( "toplevel" );
$window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );
$window->set_title( "Rotating JPEG Images..." );
$window->border_width( 0 );
$box1 = new Gtk::VBox( $false, 0 );
$box1->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $false, 0 );
$box2->show();
$window->add( $box1 );
# Create the label at the top of the window
$label = new Gtk::Label( "Rotating JPEG Images...\n" );
$box2->pack_start( $label, $false, $false, 0);
$label->show();
# Create the progress bar
$pbar = new Gtk::ProgressBar();
$box2->pack_start( $pbar, $true, $true, 0);
$pbar->show();
$separator = new Gtk::HSeparator();
$box1->pack_start( $separator, $false, $false, 0 );
$separator->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $true, 0 );
$box2->show();
# Create the close button
$button = new Gtk::Button( "Cancel" );
$button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );
$box2->pack_start( $button, $true, $true, 0 );
$button->can_default( $true );
$button->grab_default();
$button->show();
$window->show();
Gtk->main_iteration while ( Gtk->events_pending );
# set up loop to go through files passed to script
# rotate each script, increment the file number, and then update the status
# for now, assume that they are all jpegs, and do not put up a warning
$filenum = 0;
$random_file = "/tmp/rotate-image-" . time;
foreach $file (@ARGV) {
++$filenum;
$label->set_text( "Rotating JPEG Image:\n$file" );
$pbar->set_value( ( 100 * $filenum ) / ( $#ARGV + 1 ) );
print( "\"$file\"\n$random_file\n" );
system( "jpegtran -copy all -flip horizontal \"$file\" 2>&1 > $random_file" );
if ( $? == 0 )
{
system( "mv -f $random_file \"$file\"" );
}
else
{
# an error occurred in the jpegtran... for now, just leave it alone. we can analyze the error, and put up a dialog
# as soon as i figure out how to do that with gtk-perl (well)
}
system( "rm -f $random_file" );
Gtk->main_iteration while ( Gtk->events_pending );
}
$button->child->set( "Done" );
main Gtk;
exit( 0 );
==== nautilus-scripts/Varios/Multimedia/Naudilus ====
$ cat nautilus-scripts/Varios/Multimedia/Naudilus
#!/bin/bash
# Naudilus - Nautilus script for audio file conversion
# by Rafael Rigues <
# Translations and feedback are welcome!
# Depends on lame (3.91 recommended), gidalog and vorbis tools and libraries (rc 3 or newer)
# Based on code from convert_to_jpeg (David Westlund)
# Based on code from Archiver/Unarchiver (Patrick Largey & David Westlund)
# Thanks to Aur\E9lio Marinho Jargas for miscellaneous help
# Put on ~/.gnome/nautilus-scripts, and chmod +x it!
# Changelog:
# 03/17/2002 * Version 0.5
# * Info: This version was finished on 03/05/2002, and was meant for personal use only.
# (at least until I had implemented everything I wanted). However, I'm releasing it now
# to get feedback from other users.
# * I've discovered the cause for oggenc always encoding files at 342 kbps. It seems to
# be a bug triggered by the combination of glibc-2.2.4-19.3 and vorbis rc 1. Upgrading
# the vorbis tools and libraries to rc 3 solved the problem.
# * I've also found that not all versions of lame have the --decode option. I don't know
# when it was added to lame (and I'm too lazy to check the changelog now), but I'm
# using lame 3.91.
# * Now I'm using pipes to decode/encode the file simultaneously (thanks to FRS for being
# so persistent about this), so there's no need to create (and delete, afterwards) a
# temporary WAV file. It's also one less thing to check if it will be overwritten or not.
# * More code cleanups. "...Smarter! Stronger! More Aggressive! I feellike I could..." :)
# * Now also converts WAVE files to MP3 or Vorbis!
# 03/03/2002 * Version 0.4
# * Spent a whole day trying to reorganize the code, tighten it up and make it look
# smarter and prettier. Did I succeed? :)
# * Now Naudilus detects if the file exists (both the temporary .wav file created during
# the conversion and the resulting .mp3 or .ogg file) and asks the user if he wants the
# the file to be overwritten. If not, the file is ignored, and Naudilus will proceed
# with the next file.
# * I've found a strange bug where oggenc is now ALWAYS encoding the files at an average
# 342 Kbps, regardless of the arguments I pass to it. I suspect it is a fault on the ogg
# encoder, caused by a full-scale system update (which included a new version of glibc) I
# did today. I will find out more about this tomorrow, when I test the script on my
# machine at work.
# 03/02/2002 * Version 0.3
# * Naudilus now asks which format to convert the files to. Note that if you choose
# to convert a file to it's current format (eg. convert an MP3 file to MP3), it
# will be simply ignored, and Naudilus will proceed with the next file.
# * Possible conversions are: MP3 -> WAV, Ogg -> WAV, MP3 -> Ogg and Ogg -> MP3.
# 03/01/2002 * Version 0.2
# * Changed the name to "Naudilus". Thanks to Fabio Ricardo Schmidlin for the name!
# * Detects the filetype before attempting to convert the file.
# * Uses the file extension to determine which kind of file it is, if the filetype
# detection fails.
# * Added Vorbis to MP3 conversion.
# 02/28/2002 * First version. It seems to work! :)
# And now, the incredible, ever expanding TO-DO list!!
# * Check for write permission before trying to create a file. If such permission does not exist, ask
# the user where to write the file.
# * Recurse directories and subdirectories (Dangerous??)
# * Generate MP3/Ogg files with complete tags (artist, album, genre, etc...). Grab the tags from the
# original MP3/Ogg file
# Talk is cheap! Now show me the code!!!
# Version number
version="0.5"
# Messages
# English, by Myself
wait="Naudilus "$version" - Please Wait..."
warning="Naudilus "$version" - WARNING!"
converting="Converting your audio files. Get some coffee and come back later"
which_format="Convert files to which format?"
format_mp3="Mpeg Layer III (MP3)"
format_ogg="Ogg Vorbis"
format_wav="Microsoft WAV"
overwrite="The file: "
proceed=" will be overwritten. Proceed?"
case $LANG in
pt* )
# Brazilian Portuguese, also by Myself
wait="Naudilus "$version" - Aguarde..."
warning="Naudilus "$version" - AVISO!"
converting="Convertendo seus arquivos de \E1udio. Pegue um caf\E9 e volte mais tarde"
which_format="Converter arquivos para qual formato?"
format_mp3="Mpeg Layer III (MP3)"
format_ogg="Ogg Vorbis"
format_wav="Microsoft WAV"
overwrite="O arquivo: "
proceed=" ser\E1 sobrescrito. Devo continuar?";;
fr* )
wait=3D"Naudilus "$version" - Veuillez patienter..."
warning=3D"Naudilus "$version" - ATTENTION!"
converting=3D"La conversion de vos fichiers audio est en cours, veuillez prendre un caf=E9 et revenir plus tard"
which_format=3D"Dans quel format voulez-vous convertir le(s) fichier(s)?"
format_mp3=3D"Mpeg Layer III (MP3)"
format_ogg=3D"Ogg Vorbis"
format_wav=3D"Microsoft WAV"
overwrite=3D"Le fichier : "
proceed=3D" sera =E9cras=E9, voulez-vous poursuivre?";;
eo* )
wait="Naudilus "$version" - Bonvolu atendi..."
warning="Naudilus "$version" - AVERTU!"
converting="Konvertas viajn aŭdiajn dosierojn. Trinku iom da kafo kaj revenu poste."
which_format="Konvertu dosierojn al kiu formato?"
format_mp3="Mpeg Layer III (MP3)"
format_ogg="Ogg Vorbis"
format_wav="Microsoft WAV"
overwrite="La dosiero: "
proceed=" estas superskribota. \C4?u procedu?";;
sv*)
wait="Naudilus "$version" - Var god v\E4nta..."
warning="Naudilus "$version" - Varning!"
converting="Konverterar dina ljudfiler. H\E4mta lite kaffe och kom tillbaks senare"
which_format="Vilket format ska filerna konverteras till?"
format_mp3="Mpeg Lager III (MP3)"
format_ogg="Ogg Vorbis"
format_wav="Microsoft WAV"
overwrite="Filen: "
proceed=" Kommer skrivas \F6ver. Vill du forts\E4tta?";;
esac
# Select file format to convert file to
selected_format=`gdialog --title "Naudilus "$version"" --radiolist "$which_format" 260 100 3 ".ogg" "$format_ogg" on ".mp3" "$format_mp3" off ".wav" "$format_wav" off 2>&1`
if [ "$selected_format" != "" ]
then
# Do Nothing...
echo "$selected_format" > /dev/null
else
exit 0
fi
# Warn the user that the conversion will take a LONG time...
gdialog --title "$wait" --msgbox "$converting" 100 100&
# Do the conversion
while [ $# -gt 0 ]; do
in_file=$1
out_file=`echo "$in_file" | sed 's/\.\w*$/'$selected_format'/'`
while `true`; do
# Is the input file different from the output file?
if [ "$in_file" = "$out_file" ]
then
# No, break and go to the next file...
break
fi
# Does the output file exists? If yes, asks the user if he wants to
# overwrite.
if [ "`ls "$out_file" | grep -v "^ls"`" != "" ]
then
if !(`gdialog --title "$warning" --yesno "$overwrite \"$out_file\"$proceed" 200 100`)
then
# Don't owerwrite, so we get out of here.
break
fi
fi
# Lets see... Is it an MP3 file?
# Some MP3 files created with Apple's iTunes or some Windows encoders
# do not report the correct filetype when the 'file' command is used
# (it says "data", instead of "MP3, xxx kBits, xx.x kHz, Stereo...").
# So, we need to also check the file extension, and hope it's a real
# MP3 file...
if [ "`file -b "$1" | grep 'MP3'`" != "" ] || [ "`echo $in_file | grep -i '\.mp3$'`" != "" ]
then
if [ "$selected_format" = ".ogg" ]
then
lame --quiet --decode "$in_file" - | oggenc - -Q -b 128 -M 160 -o "$out_file"
else
lame --quiet --decode "$in_file" "$out_file"
fi
break
fi
# Hmmm... Does not have an MP3 signature, nor .mp3 extension. Maybe
# an Ogg-Vorbis file? Just to be sure, we also check the file extension
if [ "`file -b "$1" | grep 'Vorbis'`" != "" ] || [ "`echo $in_file | grep -i '\.ogg$'`" != "" ]
then
if [ "$selected_format" = ".mp3" ]
then
ogg123 -q --device=wav "$in_file" -f - | lame --quiet -m auto -v -F -b 128 -B 160 -h - "$out_file"
else
ogg123 -q --device=wav "$in_file" -f "$out_file"
fi
break
fi
# The last resort is to see if it is a .WAV file.. Also checking
# the file extension, of course!
if [ "`file -b "$1" | grep 'WAVE'`" != "" ] || [ "`echo $in_file | grep -i '\.wav$'`" != "" ]
then
if [ "$selected_format" = ".mp3" ]
then
lame --quiet -m auto -h -v -F -b 128 -B 160 "$in_file" "$out_file"
else
oggenc "$in_file" -Q -b 128 -M 160 -o "$out_file"
fi
break
fi
break
shift
done
shift
done
# Kill the warning
kill `ps -ef | grep "gdialog --title" | gawk '{ print $8, $2}' | grep gdialog | gawk '{ print $2 }'` 2> /dev/null
==== nautilus-scripts/Varios/Multimedia/Play_in_XMMS ====
$ cat nautilus-scripts/Varios/Multimedia/Play_in_XMMS
#!/usr/bin/python
#
# simple script to recurse a subtree, find all the mp3 and queue them to
# XMMS.
#
# Please modify this script! My python is rusty at best.
#
# Travis Hume -- travis@usermail.com
# Thu Oct 24 11:06:54 2002
#
# Barak Korren - ifireball@yahoo.com
# Sat Apr 03 2004
# Some bugfixes, now preserves alphanumerical file-ordering in
# sub-directories
import sys, glob, os, os.path, dircache
def isAudioFile( f ):
# to support additional file types just add their appropriate
# extentions to this list (lower case).
file_types = ['.mp3','.ogg','.wav']
p,ext = os.path.splitext(f)
try:
file_types.index(ext.lower())
except:
return False
return True
# change this to something other than None to make the script
# follow symlinks
follow_links = None
def find_mp3s( dirs=None ):
""" finds all mp3 files rooted at dirs and returns them as a list """
if not dirs:
return []
mp3s = []
while dirs:
if os.path.isfile(dirs[0]) and isAudioFile(dirs[0]):
mp3s.append(dirs[0])
dirs = dirs[1:]
elif os.path.isdir(dirs[0]):
found_dirs = []
for f in dircache.listdir( dirs[0] ):
p = dirs[0] + "/" + f;
if os.path.isfile(p) and isAudioFile(p):
mp3s.append( p )
elif os.path.isdir( p ) and not f.endswith( "/proc" ):
if not os.path.islink( p ) or follow_links:
found_dirs.append( p )
dirs = found_dirs + dirs[1:]
return mp3s
dirs = sys.argv[1:]
dirs.reverse()
mp3s = find_mp3s( dirs )
#inf = "";
#for mp3 in mp3s:
# inf = inf + '"' + mp3 + '"' + "\n"
#os.execvp("zenity", ['zenity','--info','--text=' + inf] )
os.execvp("xmms", ['xmms','-p'] + mp3s )
==== nautilus-scripts/Varios/Multimedia/queue_to_xmms ====
$ cat nautilus-scripts/Varios/Multimedia/queue_to_xmms
#!/usr/bin/python
#
# simple script to recurse a subtree, find all the mp3 and queue them to
# XMMS.
#
# Please modify this script! My python is rusty at best.
#
# Travis Hume -- travis@usermail.com
# Thu Oct 24 11:06:54 2002
import sys, glob, os, os.path
FALSE,TRUE = 0,1
def isAudioFile( f ):
# to support additional file types just add their appropriate
# extentions to this list (lower case).
file_types = ['.mp3','.ogg','.wav']
p,ext = os.path.splitext(f)
try:
file_types.index(ext.lower())
except:
return FALSE
return TRUE
# change this to something other than None to make the script
# follow symlinks
follow_links = None
def find_mp3s( dirs=None ):
""" finds all mp3 files rooted at dirs and returns them as a list """
if not dirs:
return []
mp3s = []
while dirs:
if os.path.isfile(dirs[0]) and isAudioFile(dirs[0]):
mp3s.append(dirs[0])
else:
found_dirs = []
for f in glob.glob( dirs[0] + "/*" ):
if os.path.isfile(f) and isAudioFile(f):
mp3s.append( f )
if os.path.islink( f ):
if follow_links:
found_dirs.append( f )
elif os.path.isdir( f ) and not f.endswith( "/proc" ):
found_dirs.append( f )
dirs = found_dirs + dirs[1:]
return mp3s
dirs = sys.argv[1:]
dirs.reverse()
mp3s = find_mp3s( dirs )
os.execvp("xmms", ['xmms','-p']+mp3s )
==== nautilus-scripts/Varios/Multimedia/Queue_to_XMMS ====
$ cat nautilus-scripts/Varios/Multimedia/Queue_to_XMMS
#!/usr/bin/perl -Wall
#
my @mp3s = reverse (@ARGV);
foreach (@mp3s) {
system ("xmms -e \"$_\"");
}
==== nautilus-scripts/Varios/Multimedia/rotate ====
$ cat nautilus-scripts/Varios/Multimedia/rotate
#!/usr/bin/perl -w
# created on Mon Jul 16 17:21:44 EDT 2001
# Matt Doller
# Alex Bennee
#
# some code is borrowed from a script i found on tigert's web site
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
### Instructions for Use:
# 1. If used on a remote file system (e.g. NFS mount) you need to parse
# the NAUTILUS_URI environment variables to get your files.
#
# 2. Having two scripts do the same thing is wasteful (and cut and and
# paste error prone) so this script decides what its going to do based on
# the name of the script (so you symlink "rotate right" and "rotate left"
# to the same file).
#
# 3. Now need for a system call to remove files. unlink will work
#
use Gtk;
use strict;
(my $me = $0) =~ s|.*/(.*)|$1|;
set_locale Gtk;
init Gtk;
my $false = 0;
my $true = 1;
my $window;
my $box1;
my $box2;
my $label;
my $pbar;
my $button;
my $separator;
my $file;
my $filenum;
my $random_file;
# Create the window
$window = new Gtk::Window( "toplevel" );
$window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );
$window->set_title( "Rotating JPEG Images..." );
$window->border_width( 0 );
$box1 = new Gtk::VBox( $false, 0 );
$box1->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $false, 0 );
$box2->show();
$window->add( $box1 );
# Create the label at the top of the window
$label = new Gtk::Label( "Rotating JPEG Images...\n" );
$box2->pack_start( $label, $false, $false, 0);
$label->show();
# Create the progress bar
$pbar = new Gtk::ProgressBar();
$box2->pack_start( $pbar, $true, $true, 0);
$pbar->show();
$separator = new Gtk::HSeparator();
$box1->pack_start( $separator, $false, $false, 0 );
$separator->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $true, 0 );
$box2->show();
# Create the close button
$button = new Gtk::Button( "Cancel" );
$button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );
$box2->pack_start( $button, $true, $true, 0 );
$button->can_default( $true );
$button->grab_default();
$button->show();
$window->show();
Gtk->main_iteration while ( Gtk->events_pending );
# Decide what command we are executaing based on the calling
# name of the script (so we can symlink version)
my $command = "jpegtran -copy all ";
my $direction;
if ( $me =~ /right/ )
{
$command = $command." -rotate 90 ";
$direction = "Right";
} else {
$command = $command." -rotate 270 ";
$direction = "Right";
}
# set up loop to go through files passed to script
# rotate each script, increment the file number, and then update the status
# for now, assume that they are all jpegs, and do not put up a warning
$filenum = 0;
$random_file = "/tmp/rotate-image-" . time;
my @filelist;
# test for argv as Nautilus could just use URI's
if (@ARGV) {
@filelist=@ARGV;
} else {
#extract files from NAUTILUS_SCRIPT_SELECTED_URIS
@filelist = split ("\n", $ENV{NAUTILUS_SCRIPT_SELECTED_URIS} );
}
foreach $file (@filelist) {
$file =~ s|^file://||; # drop any file://
++$filenum;
$label->set_text( "Rotating JPEG Image $direction:\n$file" );
$pbar->set_value( ( 100 * $filenum ) / ( scalar(@filelist) + 1 ) );
system( "$command \"$file\" 2>&1 > $random_file" );
if ( $? == 0 )
{
system( "mv -f $random_file \"$file\"" );
}
else
{
# an error occurred in the jpegtran... for now, just leave it
# alone. we can analyze the error, and put up a dialog
# as soon as i figure out how to do that with gtk-perl (well)
}
print LOG "File:",$file,"\n";
unlink $random_file;
Gtk->main_iteration while ( Gtk->events_pending );
}
$pbar->set_value(100);
$button->child->set( "Done" );
main Gtk;
exit( 0 );
==== nautilus-scripts/Varios/Multimedia/rotate_image ====
$ cat nautilus-scripts/Varios/Multimedia/rotate_image
#!/bin/bash
# FILE: rotate_image --
# AUTHOR: W. Michael Petullo
# DATE: 31 May 2001
#
# Copyright (C) 2001 W. Michael Petullo
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
mogrify -rotate 90 $*
==== nautilus-scripts/Varios/Multimedia/rotate_jpg_left ====
$ cat nautilus-scripts/Varios/Multimedia/rotate_jpg_left
#!/usr/bin/perl -w
# created on Mon Jul 16 17:21:44 EDT 2001
# Matt Doller
#
# some code is borrowed from a script I found on Tigert's web site
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
use Gtk;
use strict;
set_locale Gtk;
init Gtk;
my $false = 0;
my $true = 1;
my $window;
my $box1;
my $box2;
my $label;
my $pbar;
my $button;
my $separator;
my $file;
my $filenum;
my $random_file;
# Create the window
$window = new Gtk::Window( "toplevel" );
$window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );
$window->set_title( "Rotating JPEG Images..." );
$window->border_width( 0 );
$box1 = new Gtk::VBox( $false, 0 );
$box1->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $false, 0 );
$box2->show();
$window->add( $box1 );
# Create the label at the top of the window
$label = new Gtk::Label( "Rotating JPEG Images...\n" );
$box2->pack_start( $label, $false, $false, 0);
$label->show();
# Create the progress bar
$pbar = new Gtk::ProgressBar();
$box2->pack_start( $pbar, $true, $true, 0);
$pbar->show();
$separator = new Gtk::HSeparator();
$box1->pack_start( $separator, $false, $false, 0 );
$separator->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $true, 0 );
$box2->show();
# Create the close button
$button = new Gtk::Button( "Cancel" );
$button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );
$box2->pack_start( $button, $true, $true, 0 );
$button->can_default( $true );
$button->grab_default();
$button->show();
$window->show();
Gtk->main_iteration while ( Gtk->events_pending );
# set up loop to go through files passed to script
# rotate each script, increment the file number, and then update the status
# for now, assume that they are all jpegs, and do not put up a warning
$filenum = 0;
$random_file = "/tmp/rotate-image-" . time;
foreach $file (@ARGV) {
++$filenum;
$label->set_text( "Rotating JPEG Image:\n$file" );
$pbar->set_value( ( 100 * $filenum ) / ( $#ARGV + 1 ) );
print( "\"$file\"\n$random_file\n" );
system( "jpegtran -copy all -rotate 270 \"$file\" 2>&1 > $random_file" );
if ( $? == 0 )
{
system( "mv -f $random_file \"$file\"" );
}
else
{
# an error occurred in the jpegtran... for now, just leave it alone. we can analyze the error, and put up a dialog
# as soon as i figure out how to do that with gtk-perl
}
system( "rm -f $random_file" );
Gtk->main_iteration while ( Gtk->events_pending );
}
$button->child->set( "Done" );
main Gtk;
exit( 0 );
==== nautilus-scripts/Varios/Multimedia/rotate_jpg_right ====
$ cat nautilus-scripts/Varios/Multimedia/rotate_jpg_right
#!/usr/bin/perl -w
# created on Mon Jul 16 17:21:44 EDT 2001
# Matt Doller
#
# some code is borrowed from a script i found on tigert's web site
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
use Gtk;
use strict;
set_locale Gtk;
init Gtk;
my $false = 0;
my $true = 1;
my $window;
my $box1;
my $box2;
my $label;
my $pbar;
my $button;
my $separator;
my $file;
my $filenum;
my $random_file;
# Create the window
$window = new Gtk::Window( "toplevel" );
$window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );
$window->set_title( "Rotating JPEG Images..." );
$window->border_width( 0 );
$box1 = new Gtk::VBox( $false, 0 );
$box1->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $false, 0 );
$box2->show();
$window->add( $box1 );
# Create the label at the top of the window
$label = new Gtk::Label( "Rotating JPEG Images...\n" );
$box2->pack_start( $label, $false, $false, 0);
$label->show();
# Create the progress bar
$pbar = new Gtk::ProgressBar();
$box2->pack_start( $pbar, $true, $true, 0);
$pbar->show();
$separator = new Gtk::HSeparator();
$box1->pack_start( $separator, $false, $false, 0 );
$separator->show();
$box2 = new Gtk::VBox( $false, 10 );
$box2->border_width( 10 );
$box1->pack_start( $box2, $false, $true, 0 );
$box2->show();
# Create the close button
$button = new Gtk::Button( "Cancel" );
$button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );
$box2->pack_start( $button, $true, $true, 0 );
$button->can_default( $true );
$button->grab_default();
$button->show();
$window->show();
Gtk->main_iteration while ( Gtk->events_pending );
# set up loop to go through files passed to script
# rotate each script, increment the file number, and then update the status
# for now, assume that they are all jpegs, and do not put up a warning
$filenum = 0;
$random_file = "/tmp/rotate-image-" . time;
foreach $file (@ARGV) {
++$filenum;
$label->set_text( "Rotating JPEG Image:\n$file" );
$pbar->set_value( ( 100 * $filenum ) / ( $#ARGV + 1 ) );
print( "\"$file\"\n$random_file\n" );
system( "jpegtran -copy all -rotate 90 \"$file\" 2>&1 > $random_file" );
if ( $? == 0 )
{
system( "mv -f $random_file \"$file\"" );
}
else
{
# an error occurred in the jpegtran... for now, just leave it alone. we can analyze the error, and put up a dialog
# as soon as i figure out how to do that with gtk-perl (well)
}
system( "rm -f $random_file" );
Gtk->main_iteration while ( Gtk->events_pending );
}
$button->child->set( "Done" );
main Gtk;
exit( 0 );
==== nautilus-scripts/Varios/Multimedia/scale_image ====
$ cat nautilus-scripts/Varios/Multimedia/scale_image
#!/bin/bash
title="Scale image"
scale="Size to scale to
case $LANG in
sv* )
title="Skala bild"
scale="Storlek att skala till
esac
imgsize=`gdialog --title "$title" --inputbox "$scale" 200 100 2>&1`
while [ $# -gt 0 ]; do
picture=$1
/usr/bin/convert -scale $imgsize "$picture" "$imgsize-$picture"
shift
done
==== nautilus-scripts/Varios/Multimedia/scale_image_to_sizes ====
$ cat nautilus-scripts/Varios/Multimedia/scale_image_to_sizes
#!/bin/bash
title="Scale image"
scale="Choose which sizes to scale to"
case $LANG in
sv* )
title="Skala bild"
scale="V\E4lj storlekar att skala bilden till";;
esac
imgsize=`gdialog --title "$title" --checklist "$scale" 200 100 6 1600x1400 " " off 1280x1024 " " off 1024x768 " " off 800x600 " " off 640x480 " " off 2>&1`
while [ $# -gt 0 ]; do
picture=$1
for i in $imgsize; do
i=`echo $i | sed 's/"//g'`
/usr/bin/convert -scale $i "$picture" "$i-$picture"
done
shift
done
==== nautilus-scripts/Varios/Multimedia/Show_Digital_Photo_EXIF_data ====
$ cat nautilus-scripts/Varios/Multimedia/Show_Digital_Photo_EXIF_data
#!/usr/bin/perl -w
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# EXIF Dump script for Nautilus #
# #
# Shows various things modern digital cameras embed in the image files #
# like exposure time and aperture and other interesting information. #
# #
# Depends on gdialog for the display part and jhead for the actual #
# EXIF data parsing from the images. You can get jhead from #
# http://www.sentex.net/~mwandel/jhead/, it probably works on anything #
# that has a C compiler. Happy notice is that it does work on linux/ppc #
# as well. #
# #
# Hacked together by Tuomas Kuosmanen
# Jakub Steiner
# Released under the GPL license. #
# #
# The code is ugly, but it worksforme and this is perl. #
# My perl is ugly. -tigert- #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
use POSIX;
use Digest::MD5 qw(md5_hex);
die "No files.. Easy job." unless @ARGV;
$hash = md5_hex(localtime);
$tempfile = "/tmp/foo.$hash";
foreach $file (@ARGV) {
$reply=`jhead \"$file\" 2>&1 > $tempfile`;
# print("REPLY:: $reply\n");
if ($reply =~ "aborting") {
system("gdialog --title \"EXIF Data Error\" --msgbox \"The file $file does not contain any EXIF information.\" 100 100");
} else {
system("gdialog --title \"EXIF Information for $file\" --textbox $tempfile 34 42");
}
}
system("rm $tempfile");
==== nautilus-scripts/Varios/Multimedia/slideshow ====
$ cat nautilus-scripts/Varios/Multimedia/slideshow
#!/bin/bash
###############################################################################
# Display a fullscreen slideshow of the selected files
###############################################################################
#
# AUTHOR: Brian Connelly
# DESCRIPTION: This script displays a fullscreen slideshow of the files which
# have been selected in Nautilus.
#
# REQUIREMENTS: Nautilus file manager
# feh (see http://www.linuxbrit.co.uk)
# gdialog, which is usually included in the gnome-utils package
#
# INSTALLATION: GNOME 1.4.x: copy this script to the ~/Nautilus/scripts
# directory
# GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory
#
# USAGE: Select the files that you would like to display in Nautilus,
# right click, go to Scripts, and then select this script.
# You will then be asked to enter a Delay time. This is the
# length of time that each image will be shown. If you enter
# 0, the image will be displayed until you either click on the
# image, hit the right arrow, hit N or n, or the space key.
# For more options, run "feh --help" (without quotation marks)
#
# VERSION INFO:
# 0.1 (20020923) - Initial public release
#
# COPYRIGHT: Copyright (C) 2002 Brian Connelly
#
# LICENSE: GNU GPL
#
###############################################################################
DELAY=$(gdialog --title "Slideshow Properties" --inputbox "Enter Delay (Seconds)" 20 50 0 2>&1) || exit
DELAY=1
if [ $DELAY -eq 0 ]; then
feh --title "Slideshow" -rFx -S name $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
else
feh --title "Slideshow" -rFx -S name -D $DELAY
$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
fi
==== nautilus-scripts/Varios/Multimedia/watermark ====
$ cat nautilus-scripts/Varios/Multimedia/watermark
#!/bin/bash
#
# watermark.sh
# $Id: watermark,v 1.1 2004/10/03 10:52:21 ullgren Exp $
#
# Add a defined watermark to a series of pictures
#
# Absolute Location of the Watermark file
WM="/home/hajo/data/Pics/Var/watermark.gif"
if [ ! -n "$1" ]
then
zenity --error --text "Please select Pics to be watermarked!"
exit $E_BADARGS
fi
typeset -i CNT=1
typeset -i CUR=0
(
for pic in "$@"
do
echo "#Watermarking $pic"
composite -gravity SouthEast "$WM" "$pic" "$pic"
CUR=$CNT*100/$#
echo $CUR
CNT=$CNT+1
done
) | zenity --progress --auto-close --percentage=0
==== nautilus-scripts/Varios/Multimedia/XMMS_Enqueue ====
$ cat nautilus-scripts/Varios/Multimedia/XMMS_Enqueue
#!/bin/bash
# Description: Nautilus script that enqueues files in XMMS by the order selected
#
# Author: Celso Pinto
#
# Copyright (C) 2003 Celso Pinto
# Licence: GNU GPL
#
# Dependency: wc,bash,head,tail,xmms
#
#$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS - new line separated file paths; passed on by Nautilus on Gnome 2.2
echo "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" > /tmp/xmmsselected
numlines=`wc -l /tmp/cpinto.xmmsselected | awk '{print $1}'`
for ((i=$numlines; i>0; i--))
do
mediafile=`head -n$i /tmp/xmmsselected | tail -n1`
xmms -e $mediafile
done
==== nautilus-scripts/Varios/Obsolete/bzip2 ====
$ cat nautilus-scripts/Varios/Obsolete/bzip2
#!/bin/sh
#
# BZIP2 wrapper for Nautilus Scripts menu.
#
# AUTHOR: Roberto Piscitello
# DATE: 21 May 2001
# LICENSE: GPL
#
# We need gdialog or xmessage to output error messages
GDIALOG="/usr/bin/gdialog"
XMESSAGE="/usr/bin/X11/xmessage"
TMP_FILE=`tempfile`
IFS="
"
trap "rm -f $TMP_FILE" EXIT
for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
cd `dirname $F`
if ! bzip2 `basename $F` 2> $TMP_FILE; then
# Some error happened: beep and show an error message
echo -e "\007"
if [ -x $GDIALOG ]; then
gdialog --title bzip2 --msgbox "`cat $TMP_FILE`." 20 100
elif [ -x $XMESSAGE ]; then
xmessage -buttons OK -file $TMP_FILE
fi
fi
done
==== nautilus-scripts/Varios/Obsolete/converter ====
$ cat nautilus-scripts/Varios/Obsolete/converter
#!/bin/sh
# Copyright (C) Sept 13, 2001 Shane Mueller
# http://www-personal.umich.edu/~smueller/Nautilus-Scripts
#
# pprint: This script designed for use with the Nautilus File Manager
# This script requires the unix utility enscript, and may require
# modification based upon your local printing command.
# It will either print directly to the default printer or
# will generate a pretty file from the selected text files, and either
# print to printer or generate files from selected files.
#
# This does file-type sensitive selection.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#First, process each of the selected file
#Change these to their proper system-dependent locations
CONVERT_PATH=/usr/bin/ #Path to Imagemagick convert.
ENSCRIPT_PATH=/usr/bin #Path to enscript utilities.
OGG_PATH=/usr/bin/ #Pat to ogg utilities.
GHOSTSCRIPT_PATH=/usr/bin #Path to ghostscript utilities.
ALIEN_PATH=/usr/bin #Path to alien.
LAME_PATH=/usr/bin #Path to LAME mp3 encoder
ABI_PATH=/usr/bin #Path to abiword binary.
UNRAR_PATH=/usr/local/bin #Path to unrar binary.
UNZIP_PATH=/usr/bin #Path to unzip binary.
UNACE_PATH=/usr/local/bin #Path to unace binary.
UNARJ_PATH=/usr/bin #Path to unarj binary.
BUNZIP2_PATH=/usr/bin #Path to bzip2 binary.
GUNZIP_PATH=/usr/bin #Path to gunzip binary.
TAR_PATH=/bin #Path to tar binary.
for arg
do
FILETYPE=$(file "$arg")
#Do file-type sensitive processing
case "$FILETYPE" in
*text*) #Any type of Text file
#This allows you to select how the file is processed
choice=`gdialog --menu "How should I process this file?" 200 200 4 '1' "Print" '2' "Make .ps" '3' "Make .html" '4' "Make .rtf" 2>&1`
case $choice in
1) ##print using enscript
enscript -2 -G2rE -U1 --borders --word-wrap "$arg"
;;
2) ##print to a .ps file of your choice
NEWNAME=`gdialog --title "Generate Postscript File" --inputbox "Enter Filename (include extension)" 200 100 "$arg".ps 2>&1`
enscript -2 -G2rE -U1 --borders --word-wrap -p "$NEWNAME" "$arg"
;;
3) ##Generate an .html
NEWNAME=`gdialog --title "Generate .html" --inputbox "Enter Filename (include extension)" 200 100 "$arg".html 2>&1`
enscript -E --color -W html -p "$NEWNAME" "$arg"
;;
4) ##Generate an .rtf
NEWNAME=`gdialog --title "Generate .rtf" --inputbox "Enter Filename (include extension)" 200 100 "$arg".rtf 2>&1`
enscript -E -W rtf -p "$NEWNAME" "$arg"
;;
*) ##Don't do nothing-cancel key
;;
esac
##Other file types can go here if you know how to process them.
*postscript*)
*)
gdialog --msgbox "Uncertain how to process file $arg: \n File type $filetype" 200 200
esac
done
==== nautilus-scripts/Varios/Obsolete/create_file ====
$ cat nautilus-scripts/Varios/Obsolete/create_file
#!/usr/bin/perl -w
#
# Released under the terms of GNU GPL v 2.0 or later
#
# Copyright (C) David Westlund
#
# You will need libgtk-perl to run this program.
#
# NOTE: This script is a little buggy, and doesn't operate as expected.
# Please contribute any bugfixes to smueller@umich.edu.
#
# Config
$template_directory = $ENV{HOME} . "/Nautilus/skript/.mallar/";
# For Gtk
use Gtk;
init Gtk;
set_locale Gtk;
# For cwd, used to get the current directory
use Cwd;
my $true = 1;
my $false = 0;
# These will be used as gtk-widgets
my $window;
my $vbox;
my $hbox_1;
my $hbox_2;
my $filename_label;
my $filename_entry;
my $create_button;
# This are for the menu;
my $opt;
my $menu;
my @menu_item;
# Non-widgets for the menus...
my $i;
my $application;
my $end;
#Other variables
my $cwd = cwd;
# The gtk-signals
my $signal;
$window = new Gtk::Window( 'toplevel' );
$signal = $window->signal_connect( 'delete_event', sub { Gtk->exit( 0 ); } );
$window->border_width( 5 );
$window->set_title( "Create file" );
$vbox = new Gtk::VBox ( $false, 0 );
$window->add( $vbox );
$vbox->show ();
$hbox_1 = new Gtk::HBox ( $false, 0 );
$vbox->pack_start ($hbox_1, $false, $false, 0);
$hbox_1->show();
$filename_label = new Gtk::Label ( "Filename: " );
$hbox_1->pack_start ($filename_label, $false, $false, 0);
$filename_label->show();
$filename_entry = new Gtk::Entry ();
$hbox_1->pack_start ($filename_entry, $false, $false, 0);
$filename_entry->set_usize ( 100, undef );
$filename_entry->show();
# Row nr two
$hbox_2 = new Gtk::HBox ( $false, 0 );
$vbox->pack_start ($hbox_2, $false, $false, 0);
$hbox_2->show();
# Create the button
$create_button = new Gtk::Button ( "Create file" );
$create_button->signal_connect ('clicked', \&create_file );
$hbox_2->pack_start ($create_button, $false, $false, 0);
$create_button->show();
# Creating the menu
$opt = new Gtk::OptionMenu ();
$menu = new Gtk::Menu ();
$i = 0;
chdir $template_directory;
while (<*>) {
$application = $_;
$end = $_;
$application =~ s/\..*//;
$end =~ s/$application//;
$menu_item[$i] = new Gtk::MenuItem ( "$application" );
$menu_item[$i]->signal_connect ( 'activate', \&create_app_file, $application, $end);
$menu->append ($menu_item[$i]);
$menu_item[$i]->show ();
$i++;
}
$opt->set_menu ($menu);
$opt->show ();
$hbox_2->pack_start ($opt, $false, $false, 0);
$window->show ();
main Gtk;
sub create_file
{
my $filename;
$filename = $filename_entry->get_text ();
$filename = $cwd . "\/$filename";
system (": > $filename");
Gtk->exit (0);
}
sub create_app_file
{
my ($info, $application, $end) = @_;
my $filename;
my $template;
$filename = $filename_entry->get_text ();
$filename = $filename . $end;
$filename = $cwd . "\/$filename";
$template = $application . $end;
system ("cp $template_directory/$template $filename");
Gtk->exit (0);
}
==== nautilus-scripts/Varios/Obsolete/create_targz ====
$ cat nautilus-scripts/Varios/Obsolete/create_targz
#!/bin/bash
#
# Nautilus script -> make one tar.gz with the selected files
#
# Owner : Largey Patrick Switzerland
# naze.man@bluewin.ch
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Ver: 0.9.5-1
# Some correction in gdialog with ver 0.9.4
# thank's all for your job (sorry for my english)
#
# Ver: 0.9.4
# Date: 11.05.2001
# Support for swedish
# Don't create files with names like archive.tar.gz.tar.gz or archive.tgz.tar.gz
# If the input is just one file, the archive will be called
# Added by David Westlund
#
# Ver: 0.9.3
# Date: 10.09.2001
# nazeman added file mit space !!!
#
# Ver: 0.9.2
# Date: Sept 9, 2001
# nazeman added confirm windows + German Support
#
#
# Ver: 0.9.1
# Date: Sept 5, 2001
# Shane Mueller added patch from Manuel Clos to add Spanish support
#
# Ver : 0.9
# Date : 11.08.2001
#
# Dependence : Nautilus (of course)
# Gnome-utils (gdialog)
#
case $LANG in
fr* )
filename="Nom du Fichier ?"
fileexist="Fichier existant, \E9craser ?"
title="Archiveur "
archive="archive"
rec="est enregistr\E9" ;;
es* )
filename="\BFNombre del archivo?"
fileexist="El archivo ya existe, \BFsobreescribir?"
title="Archivar en tar.gz"
archive="?????"
rec="????" ;;
de* )
filename="Dateiname ?"
fileexist="Datei existiert bereits, \FCberschreiben ?"
title="Archiv erstellen"
archive="archiv"
rec="ist gespeichert" ;;
sv* )
filename="Filnamn?"
fileexist="Filen existerar, vill du skriva \F6ver?"
title="tar.gz-arkiverare"
archive="arkiv"
rec="\E4r sparad" ;;
* )
filename="File name ?"
fileexist="File exist, owerwrite ?"
title="tar.gz maker"
archive="archive"
rec="is saved" ;;
esac
if [ $# = 1 ]; then
archive=`echo $1 | sed 's/.tar.gz//'`
fi
if
nom=`gdialog --title "$title" --inputbox "$filename" 200 100 "$archive" 2>&1`
then
nom=`echo $nom | sed 's/.tar.gz//'`
while [ -f ./$nom.tar.gz ]
do
if
gdialog --title "$title" --defaultno --yesno "$fileexist" 200 100 ;
then
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\\ /g'`
if [ -f ./$nom.tar ]
then
tar -rf ./$nom.tar "$files" ;
else
tar -cf ./$nom.tar "$files";
fi
shift
done
gzip -9f ./$nom.tar ;
gdialog --msgbox "$PWD/$nom.tar.gz $rec" 200 100 ;
exit 0 ;
else
if
nom=`gdialog --title "$title" --inputbox "$filename" 200 100 "$archive" 2>&1`
then
continue ;
else
exit 0 ;
fi
fi
done
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\\ /g'`
if [ -f ./$nom.tar ]
then
tar -rf ./$nom.tar "$files" ;
else
tar -cf ./$nom.tar "$files";
fi
shift
done
gzip -9 ./$nom.tar ;
gdialog --msgbox "$PWD/$nom.tar.gz $rec" 200 100 ;
fi
==== nautilus-scripts/Varios/Obsolete/create-zip ====
$ cat nautilus-scripts/Varios/Obsolete/create-zip
#!/bin/sh
# create-zip
# From: Manuel Clos
# Nautilus script -> make one zip with the selected file
#
# Dependence : Nautilus (of course)
# Gnome-utils (gdialog)
#
case $LANG in
es* )
filename="\BFNombre del archivo?"
fileexist="El archivo ya existe, \BFsobreescribir?"
title="Archivar en zip" ;;
fr* )
filename="Nom du Fichier ?"
fileexist="Fichier existant, \E9craser ?"
title="Archiveur zip" ;;
* )
filename="File name ?"
fileexist="File exist, owerwrite ?"
title="zip maker" ;;
esac
if
nom=`gdialog --title "$title" --inputbox "$filename " 200 100 2>&1`
then
while [ -f ./$nom.zip ]
do
if
gdialog --title "$title" --defaultno --yesno "$fileexist" 200 100
then
zip -r ./$nom.zip $@ ;
exit 0 ;
else
if
nom=`gdialog --title "$title" --inputbox "$filename" 200 100 2>&1`
then
next ;
else
exit 0 ;
fi
fi
done
zip -r ./$nom.zip $@ ;
fi
==== nautilus-scripts/Varios/Obsolete/gb-unzip ====
$ cat nautilus-scripts/Varios/Obsolete/gb-unzip
#!/bin/sh
#
# GUNZIP and BUNZIP2 wrapper for Nautilus Scripts menu.
#
# AUTHOR: Roberto Piscitello
# DATE: 21 May 2001
# LICENSE: GPL
#
# We need gdialog or xmessage to output error messages
GDIALOG="/usr/bin/gdialog"
XMESSAGE="/usr/bin/X11/xmessage"
TMP_FILE=`tempfile`
IFS="
"
trap "rm -f $TMP_FILE" EXIT
for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
cd `dirname $F`
if [ `echo $F|awk '{ print substr($0,length($0)-2) }'` = "bz2" -o `echo $F|awk '{ print substr($0,length($0)-1) }'` = "bz" ]; then
UZIP="bunzip2"
else
UZIP="gunzip"
fi
if ! $UZIP `basename $F` 2> $TMP_FILE; then
# Some error happened: beep and show an error message
echo -e "\007"
if [ -x $GDIALOG ]; then
gdialog --title $UZIP --msgbox "`cat $TMP_FILE`." 20 100
elif [ -x $XMESSAGE ]; then
xmessage -buttons OK -file $TMP_FILE
fi
fi
done
==== nautilus-scripts/Varios/Obsolete/gzip ====
$ cat nautilus-scripts/Varios/Obsolete/gzip
#!/bin/sh
#
# GZIP wrapper for Nautilus Scripts menu.
#
# AUTHOR: Roberto Piscitello
# DATE: 21 May 2001
# LINCENSE: GPL
#
# We need gdialog or xmessage to output error messages
GDIALOG="/usr/bin/gdialog"
XMESSAGE="/usr/bin/X11/xmessage"
TMP_FILE=`tempfile`
IFS="
"
trap "rm -f $TMP_FILE" EXIT
for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do
cd `dirname $F`
if ! gzip `basename $F` 2> $TMP_FILE; then
# Some error happened: beep and show an error message
echo -e "\007"
if [ -x $GDIALOG ]; then
gdialog --title gzip --msgbox "`cat $TMP_FILE`." 20 100
elif [ -x $XMESSAGE ]; then
xmessage -buttons OK -file $TMP_FILE
fi
fi
done
==== nautilus-scripts/Varios/Obsolete/mail_image ====
$ cat nautilus-scripts/Varios/Obsolete/mail_image
#!/bin/sh
# FILE: mail_image --
# AUTHOR: W. Michael Petullo
# DATE: 31 May 2001
#
# Copyright (C) 2001 W. Michael Petullo
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
tmpdir=`mktemp -d /tmp/mail-image-XXXXXX`
for i in $*; do
cp $i $tmpdir
tmpfile=${tmpdir}/`basename $i`
mogrify -geometry '640x480>' $tmpfile
attachments=${attachments},${tmpfile}
done
# Get rid of the leading comma.
attachments=`echo $attachments | sed 's/^,//g'`
balsa -a "$attachments"
rm -rf $tmpdir
==== nautilus-scripts/Varios/Obsolete/mailinbalsa ====
$ cat nautilus-scripts/Varios/Obsolete/mailinbalsa
#!/bin/sh
for i in $*; do
attachments=${attachments},${i}
done
# Get rid of the leading comma.
attachments=`echo $attachments | sed 's/^,//g'`
balsa -a "$attachments"
==== nautilus-scripts/Varios/Obsolete/RPM-install-update ====
$ cat nautilus-scripts/Varios/Obsolete/RPM-install-update
#!/bin/bash
#
# Nautilus script -> Install or Update Rpm with gnorpm
#
# Owner : Largey Patrick from Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
#
# Ver: 1.0 Date: 31.03.2002
# Initial release
#
# Dependence : Nautilus (of course)
# Gdialog (Gnome-utils)
# Gnome-Rpms (gnorpms)
#
title="Rpm Installer-Updater"
rpminstaller="What do you want to make ?"
install="install"
update="update"
info="information"
case $LANG in
fr* )
title="Rpm installation ou mise \E0 jour"
rpminstaller="Que voulez-vous faire ?"
install="installation"
update="mise \E0 jour"
info="information";;
esac
filesall=""
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\?/g'`
filesall="$files $filesall"
shift
done
admin=`whoami`
if
rpmchoise=`gdialog --title "$title" --radiolist "$rpminstaller" 260 100 5 "-i" "$install" off "-U" "$update" on "-qp" "$info" off 2>&1`
then
case $rpmchoise in
-i )
if [ $admin = root ]
then
gnorpm -i $fileall&
else
gnorpm-auth -i $filesall&
fi;;
-U )
if [ $admin = root ]
then
gnorpm -U $fileall&
else
gnorpm-auth -U $filesall&
fi;;
-qp )
if [ $admin = root ]
then
gnorpm -qp $fileall&
else
gnorpm-auth -qp $filesall&
fi;;
esac
else
exit 0
fi
==== nautilus-scripts/Varios/Obsolete/to_upper ====
$ cat nautilus-scripts/Varios/Obsolete/to_upper
#!/bin/sh
echo $@
# Lower-case a filename
#Note that 'This' will overwrite 'this'!
mv -iv "$@" "`echo \"$@\" | tr A-Z a-z`"
==== nautilus-scripts/Varios/Obsolete/uncompress_all ====
$ cat nautilus-scripts/Varios/Obsolete/uncompress_all
#!/bin/bash
#
# Nautilus script -> Un Compress all format
#
# tar.gz ; tgz ; tar ; gz ; tar.bz2 ; bz2 ; zip ; rar are know
#
# Owner : Largey Patrick from Switzerland
# naze.man@bluewin.ch
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Ver: 0.9.2
# Add rar format + error dialog
#
# Ver: 0.9.1
# Date: 11.05.2001
# Support for swedish
# Added by David Westlund
#
# Ver: 0.9
# Date: 27.10.2001
#
# Dependence : Nautilus (of course)
# Gnome-utils (gdialog)
#
case $LANG in
fr* )
title="Decompacteur"
beuh="format inconnu"
ncompr="ne peut \EAtre d\E9compress\E9"
compr="est d\E9compress\E9" ;;
sv* )
title="Packa upp"
beuh="Ok\E4nt format"
ncompr="kunde inte packas upp korrekt"
compr="\E4r uppackad" ;;
* )
title="Uncompress"
beuh="Unknown format"
ncompr="could not be decompressed"
compr="is decompressed" ;;
esac
decompressed=""
errors=""
while [ $# -gt 0 ]
do
error=0
#
# tar.gz format
#
if
ext=`echo "$1" | grep [.]tar.gz$ 2>&1`
[ "$ext" != "" ]
then
tar -xzf "$1" || error=1
#
# tgz format
#
elif
ext=`echo "$1" | grep [.]tgz$ 2>&1`
[ "$ext" != "" ]
then
tar -xzf "$1" || error=1
#
# tar format
#
elif
ext=`echo "$1" | grep [.]tar$ 2>&1`
[ "$ext" != "" ]
then
tar -xf "$1" || error=1
#
# gz format
#
elif
ext=`echo "$1" | grep [.]gz$ 2>&1`
[ "$ext" != "" ]
then
gunzip -N "$1" || error=1
#
# tar.bz2 format
#
elif
ext=`echo "$1" | grep [.]tar.bz2$ 2>&1`
[ "$ext" != "" ]
then
tar -jxf "$1" || error=1
#
# bz2 format
#
elif
ext=`echo "$1" | grep [.]bz2$ 2>&1`
[ "$ext" != "" ]
then
bunzip2 -k "$1" || error=1
#
# zip format
#
elif
ext=`echo "$1" | grep [.]zip$ 2>&1`
[ "$ext" != "" ]
then
unzip "$1" || error=1
#
# rar format
#
elif
ext=`echo "$1" | grep [.]rar$ 2>&1`
[ "$ext" != "" ]
then
unrar x -kb -o+ "$1" || error=1
#
# ??? format
#
else
gdialog --title "$title" --msgbox "$1 $beuh" 200 100
error=-1;
fi
if [ $error != -1 ]; then
if [ $error = 0 ]; then
decompressed="$decompressed $1"
else
errors="$errors $1"
fi
fi
shift
done
if [ "$decompressed" != "" ]; then
gdialog --title "$title" --msgbox "$decompressed $compr" 200 100
fi
if [ "$errors" != "" ]; then
gdialog --title "$title" --msgbox "$errors $ncompr" 200 100
fi
==== nautilus-scripts/Varios/SystemConfiguration/archiver-config ====
$ cat nautilus-scripts/Varios/SystemConfiguration/archiver-config
#!/bin/bash
#
#
# Nautilus script -> Config for Archive Tool for Nautilus
# Make default config for archiver-unarchiver
#
# Owner : Largey Patrick Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Dependency : gdialog (gnome-utils) or Zenity
# archiver-unarchiver ;-)
#
# Encoding UTF-8
#
# Ver 0.9.3 Date 13.12.2003
# Add zenity ;-)
#
# Ver 0.9.2 Date 03,05,2003
# Update for Gnome 2.x
#
# Ver 0.9-1 Date 20.03.2002
# Some update and Brazilian portuguese from Rafael Rigues
#
# Ver 0.9 Date : 11.03.2002
# First release .... Configurator for archiver-unarchiver
#
title="Config for Archiver-Unarchiver"
compressormulti="Default archiver format for multiple files : "
compressorsingle="Default archiver format for single file : "
valid="available"
notvalid="not available"
format="format"
choix="choice"
noconfig="no config"
info="information"
rec="was created successfully."
case $LANG in
fr* )
title="Config de l'Archiveur-Desarchiveur"
compressormulti="Format d'archive par défaut pour de multiples fichiers : "
compressorsingle="Format d'archive par défaut pour fichier unique : "
valid="disponible"
notvalid="non disponible"
format="extension"
choix="choix"
noconfig="ne pas configurer"
info="information"
rec="est enregistré";;
de* )
title="Konfigurator von Archiver-Desarchiver"
compressormulti="Default Archiver Format für mehrere Dateien : "
compressorsingle"Default archiver Format für ein Datei : "
valid="Gültig"
notvalid="Nicht gültig"
format="Format"
choix="Choice"
noconfig="nicht konfigurieren"
rec="ist gespeichert";;
pt* )
title="Configurador para o Compactador-Descompactador"
compressormulti="Formato padrão para múltiplos arquivos : "
compressorsingle="Formato padrão para um único arquivo : "
valid="disponível"
notvalid="não disponível"
noconfig="não configurar"
rec="foi criado com sucesso.";;
es* )
title="Configuración de Archivador-Desarchivador"
compressormulti="Formato por defecto para varios ficheros : "
compressorsingle="Formato por defecto para un solo fichero : "
valid="disponible"
notvalid="no disponible"
noconfig="sin configuración"
rec="se guardó correctamente";;
esac
#
# Test binary programm
#
if which tar 2> /dev/null
then
atar="$valid"
else
atar="$notvalid"
fi
if which zip 2> /dev/null
then
azip="$valid"
else
azip="$notvalid"
fi
if which gzip 2> /dev/null
then
agzip="$valid"
else
agzip="$notvalid"
fi
if which bzip2 2> /dev/null
then
abzip2="$valid"
else
abzip2="$notvalid"
fi
if which compress 2> /dev/null
then
acompress="$valid"
else
acompress="$notvalid"
fi
if which rar 2> /dev/null
then
arar="$valid"
else
arar="$notvalid"
fi
#
# Configure default extension for archiver-unarchiver
#
if which zenity 2>/dev/null
then
#
# script with zenity
#
if
compres=`zenity --title "$compressorsingle" --width 400 --list --radiolist --column "$choix" --column "$format" --column "$info" FALSE ".zip" "$azip" FALSE ".gz" "$agzip" FALSE ".bz2" "$abzip2" FALSE ".Z" "$acompress" FALSE ".rar" "$arar" FALSE "X" "$noconfig" 2>&1`
then
compres=`echo $compres | sed 's/\"//g'`
if [ "$compres" = "X" ]
then
echo "" > ~/.archiver.conf
else
echo "single $compres" > ~/.archiver.conf
fi
else
exit 0
fi
if
compres=`zenity --title "$compressormulti" --width 400 --list --radiolist --column "$choix" --column "$format" --column "$info" FALSE ".tar.gz" "$agzip" FALSE ".tar.bz2" "$abzip2" FALSE ".zip" "$azip" FALSE ".tar" "$atar" FALSE ".rar" "$arar" FALSE "X" "$noconfig" 2>&1`
then
compres=`echo $compres | sed 's/\"//g'`
if [ "$compres" = "X" ]
then
echo "" >> ~/.archiver.conf
else
echo "multi $compres" >> ~/.archiver.conf
fi
else
exit 0
fi
zenity --title "$title" --info --text "~/.archiver.conf $rec"
else
#
# script with gdialog
#
if
compres=`gdialog --title "$title" --radiolist "$compressorsingle" 260 100 100 ".zip" "$azip" off ".gz" "$agzip" on ".bz2" "$abzip2" off ".Z" "$acompress" "off" ".rar" "$arar" "off" "X" "$noconfig" "off" 2>&1`
then
compres=`echo $compres | sed 's/\"//g'`
if [ "$compres" = "X" ]
then
echo "" > ~/.archiver.conf
else
echo "single $compres" > ~/.archiver.conf
fi
else
exit 0
fi
if
compres=`gdialog --title "$title" --radiolist "$compressormulti" 260 200 100 ".tar.gz" "$agzip" on ".tar.bz2" "$abzip2" off ".zip" "$azip" off ".tar" "$atar" off ".rar" "$arar" "off" "X" "$noconfig" "off" 2>&1`
then
compres=`echo $compres | sed 's/\"//g'`
if [ "$compres" = "X" ]
then
echo "" >> ~/.archiver.conf
else
echo "multi $compres" >> ~/.archiver.conf
fi
else
exit 0
fi
gdialog --title "$title" --msgbox "~/.archiver.conf $rec" 100 100
fi
==== nautilus-scripts/Varios/SystemConfiguration/Debian_Package ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Debian_Package
#!/bin/bash
#
# Version: 0.1
#
# This script is build to extract, install and get info about Debian packages (.deb:s)
#
# Distributed under the terms of GNU GPL version 2 or later
#
# Copyright (C) Pontus Ullgren
# Install in your Nautilus scripts directory.
#
# Credits goes to Keith Conger for his super-extractor Nautilus script which I used as
# a template.
#
FILE_TYPE=$(file -b $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|awk '{ print $1}')
MIME_TYPE=$(file -b $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS)
DEFAULT_DIR="./"`basename $1 .deb`
DPKG_PATH=/usr/bin
TEMP_FILE=`tempfile`
XTERMPRG=/usr/bin/X11/xterm
if [ "$FILE_TYPE" != "Debian" ]; then
zenity --error --title "File error" --text "$1 is not a Debian package.\nIt is reported as: $MIME_TYPE ($FILE_TYPE)" 2>&1
exit -1;
fi
TODO=$(zenity --list --radiolist --column "" --column "Action" TRUE "Extract package" FALSE "Install package" FALSE "Get info" 2>&1)
if [ "$TODO" = "Extract package" ]; then
DIR=$(zenity --title "Extract compressed file to..." --entry --text "Directory to extract to:" --entry-text "$DEFAULT_DIR" --width=500 2>&1)
if [ $DIR ]; then
mkdir $DIR
$DPKG_PATH/dpkg-deb --vextract $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $DIR/ > $TEMP_FILE
zenity --text-info --title "Extraction Log" --filename $TEMP_FILE --width=500 --height=500 2>&1
rm $TEMP_FILE
else
zenity --error --title "Action canceled" --text "Action canceled by the user." 2>&1
fi
elif [ "$TODO" = "Install package" ]; then
echo "#!/bin/sh" > $TEMP_FILE
echo "/bin/su -c \"$DPKG_PATH/dpkg --install $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS\"" >> $TEMP_FILE
echo "echo Press enter to exit ..." >> $TEMP_FILE
echo "read" >> $TEMP_FILE
$XTERMPRG -T "Installing $1" -e /bin/sh $TEMP_FILE
rm $TEMP_FILE
elif [ "$TODO" = "Get info" ]; then
$DPKG_PATH/dpkg-deb -I $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS > $TEMP_FILE
zenity --text-info --title "Info about $1" --filename $TEMP_FILE --width=500 --height=500 2>&1
rm $TEMP_FILE
fi
==== nautilus-scripts/Varios/SystemConfiguration/Hide_or_Show_Hidden_Files ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Hide_or_Show_Hidden_Files
# From dredoz on gnomesupport.org
#!/bin/sh
OLDSTATE=$(gconftool-2 --get "/desktop/gnome/file_views/show_hidden_files")
if [ "$OLDSTATE" == "false" ] ; then
NEWSTATE="True"
else
NEWSTATE="False"
fi
gconftool-2 --set "/desktop/gnome/file_views/show_hidden_files" --type boolean $NEWSTATE
==== nautilus-scripts/Varios/SystemConfiguration/Install_Galeon_Theme ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Install_Galeon_Theme
#!/bin/bash
#
#
# Nautilus script -> Install Galeon Theme (Uses Archiver-Unarchiver)
#
# Install Galeon Theme Owner: Matthew Hall
# nyquist@ntlworld.com
# http://people.ecsc.co.uk/~matt/
#
# Archiver-Unarchiver Owner : Largey Patrick Switzerland
# naze.man@bluewin.ch
# www.homepage.swissonline.ch/nazeman
# Archiver-Unarchiver Co-Owner : David Westlund
# daw@wlug.westbo.se
#
# Licence : GNU GPL
#
# Default language
#
filename="File name?"
fileexist="File exists. Overwrite?"
title="Archiver-Unarchiver"
archive="archive"
compressor="extension: archive: "
decompressor="Do you want to uncompress: "
valid="available"
notvalid="not available"
pleasewait="Please wait...."
warning="Warning!"
beuh="Unknown format."
ncompr="could not be uncompressed."
compr="has been uncompressed."
rec="was created successfully."
overwrite="The following files will be overwritten: "
proceed=". Do you want to proceed?"
theme="Theme"
installer="Installer"
installed="Installed"
case $LANG in
fr* )
filename="Nom du Fichier ?"
fileexist="Fichier existant, \E9craser ?"
title="Archiveur-Desarchiveur"
archive="archive"
decompressor="Voulez vous d\E9sarchiver : "
compressor="Extension de l'archive : "
valid="disponible"
notvalid="non disponible"
pleasewait="Veuillez patientez ....."
warning="! Attention !"
beuh="format inconnu"
ncompr="ne peut \EAtre d\E9compress\E9"
compr="est d\E9compress\E9"
rec="est enregistr\E9"
overwrite="les fichiers suivant seront \E9cras\E9: "
theme="Th\E8me"
installer="Installateur"
installed="Install\E9"
proceed=". Voulez-vous poursuirvre ?" ;;
es* )
filename="\BFNombre del archivo?"
fileexist="El archivo ya existe, \BFsobreescribir?"
title="Archivar"
archive="archivo"
compressor="\BFextensi\F3n del archivo?"
decompressor="\BF Quiere descomprimir "
valid="disponible"
notvalid="no disponible"
pleasewait="Por favor, espere..."
warning="\A1 Cuidado !"
beuh="Formato desconocido"
ncompr="no se puede descomprimir"
compr="se descomprimi\F3 correctamente."
rec="se cre\F3 correctamente"
overwrite="los archivos suiguientes ser\E1n sobreescritos: "
theme="Tema"
installer="Instalador"
installed="Instalado"
proceed=". \BF Quiere continuar ?" ;;
de* )
filename="Dateiname ?"
fileexist="Datei existiert bereits, \FCberschreiben ?"
title="Archiver-Desarchiver"
archive="archiv"
compressor="Extension von Archiv : "
decompressor="wollen Sie dekomprimieren : "
valid="G\FCltig"
notvalid="Nicht g\FCltig"
pleasewait="Bitte warten ...."
warning="! Warnung !"
beuh="unbekanntes Format"
ncompr="kann nicht dekomprimieren"
compr="ist komprimiert"
rec="ist gespeichert"
overwrite="soll(en) diese Datei(en) \FCberschriebenerden: "
theme="Thema"
installer="Installateur"
installed="Installiert"
proceed="Wollen Sie weitermachen ?" ;;
eo* )
filename="Dosiera nomo?"
fileexist="Dosiero ekzistas. \C6u superskribu?"
title="Ar\B6igilo-Malar\B6ivigilo"
archive="ar\B6ivo"
compressor="Fina\BCo de la ar\B6ivo?"
decompressor="\C6u vi volas malar\B6ivigi: "
valid="havebla"
notvalid="nehavebla"
pleasewait="Bonvolu atendi..."
warning="Avertu!"
beuh="Nekonata formato"
ncompr="Ne povis kompresigi"
compr="estas kompresigita"
rec="\F8uste kreita"
overwrite="La sekvantaj dosieroj superskribi\F8os: "
theme=""
installer=""
installed=""
proceed=". \C6u vi volas procedi?";;
pt* )
filename="Nome do arquivo?"
fileexist="O arquivo j\E1 existe. Sobrescrever?"
title="Compactador-Descompactador"
archive="arquivo"
compressor="extens\E3o: arquivo: "
decompressor="Voc\EA quer descompactar: "
valid="dispon\EDvel"
notvalid="n\E3o dispon\EDvel"
pleasewait="Aguarde...."
warning="Aviso!"
beuh="Formato desconhecido."
ncompr="n\E3o p\F4de ser descompactado."
compr="foi descompactado."
rec="foi criado com sucesso."
overwrite="Os seguintes arquivos ser\E3o sobrescritos: "
theme=""
installer=""
installed=""
proceed=". Deseja continuar?" ;;
sv* )
filename="Filnamn?"
fileexist="Filen existerar, vill du skriva \F6ver?"
title="tar.gz-arkiverare"
compressor="Fil\E4ndelse arkiv :"
decompressor="Vill du packa upp : "
archive="arkiv"
#valid="????"
#notvalid="????"
pleasewait="Var god v\E4nta..."
warning="! Varning !"
beuh="Ok\E4nt format"
ncompr="kunde inte packas upp korrekt"
compr="\E4r uppackad"
rec="\E4r sparad"
overwrite="F\F6ljande filer kommer skrivas \F6ver: "
theme=""
installer=""
installed=""
proceed=". Vill du forts\E4tta?" ;;
et* )
filename="Faili nimi?"
fileexist="Fail on juba olemas. Kas kirjutada \FCle?"
title="Arhivaator"
archive="arhiiv"
compressor="laiend: arhiiv: "
decompressor="Kas sa tahad lahti pakkida: "
valid="v\F5imalik"
notvalid="ei ole v\F5imalik"
pleasewait="Palun oota...."
warning="Hoiatus!"
beuh="Tundmatu vorming."
ncompr=": ei saa lahti pakkida."
compr="lahti pakitud."
rec="edukalt loodud."
overwrite="J\E4rgnevad failid kirjutatakse \FCle: "
theme=""
installer=""
installed=""
proceed=". Kas tahad j\E4tkata?" ;;
esac
#
# check the config file
#
if [ ! -f ~/.archiver.conf ]
then echo "" > ~/.archiver.conf
fi
#
# test archive or not
#
test_arch1=`file -b "$1" | grep 'archive'`
test_arch2=`file -b "$1" | grep 'compress'`
test_arch="$test_arch1$test_arch2"
if [ "$test_arch" != "" ]
then
#
# is one archive -> decompress
#
decompressed=""
errors=""
if gdialog --title "$title" --yesno "$decompressor $1 ?" 100 100
then
while [ $# -gt 0 ]
do
error=0
if
ext=`echo "$1" | grep [.][tT][aA][rR].[gG][zZ]$ 2>&1`
[ "$ext" != "" ]
then
tar -xzf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][tT][gG][zZ]$ 2>&1`
[ "$ext" != "" ]
then
tar -xzf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][tT][aA][rR]$ 2>&1`
[ "$ext" != "" ]
then
tar -xf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][gG][zZ]$ 2>&1`
[ "$ext" != "" ]
then
gunzip -fN "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][tT][aA][rR][.][bB][zZ]2$ 2>&1`
[ "$ext" != "" ]
then
tar -jxf "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][bB][zZ]2$ 2>&1`
[ "$ext" != "" ]
then
bunzip2 -fk "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][zZ][iI][pP]$ 2>&1`
[ "$ext" != "" ]
then
unzip -o "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][rR][aA][rR]$ 2>&1`
[ "$ext" != "" ]
then
unrar x -kb -o+ "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][zZ]$ 2>&1`
[ "$ext" != "" ]
then
uncompress -f "$1" || error=1
dir=`ls | cut -f 2 -d 'z'`
elif
ext=`echo "$1" | grep [.][aA][cC][eE]$ 2>&1`
[ "$ext" != "" ]
then
unace -e "$1" || error=1
else
gdialog --title "$title" --msgbox "$1 $beuh" 200 100
error=-1
fi
if [ $error != -1 ]
then
if [ $error = 0 ]
then
decompressed="$decompressed $1"
else
errors="$errors $1"
fi
fi
shift
done
else
exit 0
fi
else
#
# test if programm are availlable
#
if which tar 2> /dev/null
then
atar="$valid"
else
atar="$notvalid"
fi
if which zip 2> /dev/null
then
azip="$valid"
else
azip="$notvalid"
fi
if which gzip 2> /dev/null
then
agzip="$valid"
else
agzip="$notvalid"
fi
if which bzip2 2> /dev/null
then
abzip2="$valid"
else
abzip2="$notvalid"
fi
if which compress 2> /dev/null
then
acompress="$valid"
else
acompress="$notvalid"
fi
if which rar 2> /dev/null
then
arar="$valid"
else
arar="$notvalid"
fi
fi
#Copy unpackaged theme to galeon theme directory
admin=`whoami`
if [ $admin = root ]
then
cp -R $dir /usr/share/galeon/themes/
else
if [ -d ~/.galeon/themes ]
then
mv $dir ~/.galeon/themes/$dir
else
mkdir ~/galeon/themes
mv $dir ~/.galeon/themes/$dir
fi
fi
#optionally remove directory (off by default)
#rm -rf $dir
#optionally remove package (off by default)
#rm -f $1
if [ "$decompressed" != "" ]
then
gdialog --title "Galeon $theme $installer & $title" --msgbox "$theme $installed" 200 100
fi
if [ "$errors" != "" ]
then
gdialog --title "$title" --msgbox "$errors $ncompr" 200 100
fi
==== nautilus-scripts/Varios/SystemConfiguration/install_rpm ====
$ cat nautilus-scripts/Varios/SystemConfiguration/install_rpm
#!/bin/bash
gnorpm-auth -U $*
==== nautilus-scripts/Varios/SystemConfiguration/Install_to_Palm ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Install_to_Palm
#!/bin/sh
# Nautilus Script to install an application on your Palm
# Author: Andrea Grandi
# version: 0.1.0
filepath=$NAUTILUS_SCRIPT_SELECTED_URIS
gdialog --msgbox "I'm going to install $filepath on your Palm." 100 300
gpilot-install-file -n $filepath
==== nautilus-scripts/Varios/SystemConfiguration/make_launcher ====
$ cat nautilus-scripts/Varios/SystemConfiguration/make_launcher
#!/bin/sh
# Make lancher - Script to create a .desktop launcher at your Gnome desktop
# By Terje Tollefsen
makelancher() {
lname=`gdialog --inputbox "Lancher $arg name" 200 100 "$arg" 2>&1`
if [ $? -eq 1 ]; then
exit
fi
lcomment=`gdialog --inputbox "Lancher $arg comment" 200 100 "$arg" 2>&1`
if [ $? -eq 1 ]; then
exit
fi
licon=`gdialog --inputbox "Lancher $arg icon" 200 100 "gnome-ccdesktop.png" 2>&1`
if [ $? -eq 1 ]; then
exit
fi
echo [Desktop Entry] > ~/.gnome-desktop/"$arg.desktop"
echo Name=$lname >> ~/.gnome-desktop/"$arg.desktop"
echo Comment=$lcomment >> ~/.gnome-desktop/"$arg.desktop"
echo Exec=$PWD/$lexec >> ~/.gnome-desktop/"$arg.desktop"
echo Icon=$licon >> ~/.gnome-desktop/"$arg.desktop"
echo Terminal=0 >> ~/.gnome-desktop/"$arg.desktop"
echo Type=Application >> ~/.gnome-desktop/"$arg.desktop"
}
for arg
do
lexec=$arg
if [ -f ~/.gnome-desktop/"$arg.desktop" ];
then
if gdialog --title "Overwrite?" --defaultno --yesno "Launcher $arg already exist. Overwrite?" 200 100
then
makelancher
else
arg=`gdialog --inputbox ".desktop filename for $arg" 200 100 "New-$arg" 2>&1`
if [ $? -eq 1 ]; then
exit
fi
makelancher
fi
else
makelancher
fi
done
==== nautilus-scripts/Varios/SystemConfiguration/make-nautilus-script ====
$ cat nautilus-scripts/Varios/SystemConfiguration/make-nautilus-script
#!/bin/sh
# make_nautilus_script: copies the selected file(s) to ~/Nautilus/scripts
# and makes it executable. It will overwrite without warning.
for arg
do
cp "$arg" ~/.gnome/nautilus-scripts/
chmod u+x ~/.gnome/nautilus-scripts/"$arg"
done
==== nautilus-scripts/Varios/SystemConfiguration/pseudo-nautilus ====
$ cat nautilus-scripts/Varios/SystemConfiguration/pseudo-nautilus
#/bin/bash
## This is a "PSEUDO-NAUTILUS" general script.
## To run a "Nautilus" script without Nautilus, change COMMAND
## to the script of your choice. This will set all important
## environment variables that a script is likely to use, as
## well as assuring the script executes in the proper directory
##
## To use: Create a launcher in the panel, or a .desktop file that executes
## this script. By dragging selected files to this launcher, the script
## will run on the selected files in the directory of the files.
##
##
## Placed in the public domain April, 2002 by Shane T. Mueller
##
##
## Version 1.1 Apr 5, 2002 Additional fixes for files with spaces in their names, with
thanks to Patrick Largey.
## Version 1.0 April 1, 2002 Initial Release.
SCRIPTNAME=~/.gnome/nautilus-scripts/scriptname
shortnames=""
longnames=""
urls=""
for arg in "$@"
do
#Make sure that the url starts with the proper type: if the url starts with
## '/', change it to 'file:///'
url=`echo "$arg"| sed 's/^\//file:\/\/\//'`
##find the long name of the file (absolute path)
longname=`echo "$url" | sed -e 's/file:\/\///g'`
## This crazy line translates all of the %20-like url characters into their escaped
## \ actual characters. I wish I could find a cleaner way to do this.
longname=`echo "$longname" | sed -e 's/\%23/\#/g' -e 's/\%20/\ /g' -e 's/\%24/\$/g' -e 's/\%25/\%/g' -e 's/\%35/\?/g' -e 's/\%3B/\;/g' -e 's/\%3C/\/g' -e 's/\%40/\@/g' -e 's/\%5B/\[/g' -e 's/\%26/\&/g' -e 's/\%2C/\,/g' -e 's/\%5E/\^/g' -e 's/\%5D/\]/g' -e 's/\%60/\`/g' -e 's/\%7B/\{/g' -e 's/\%7C/\|/g' -e 's/\%7D/\}/g' -e 's/\ /\?/g'`
# This translation doesn't work.
# -e 's/\%5C/\\/g'`
##find the short name of the file (filename only)
shortname=`basename "$longname"`
##Mush the individual entries into a single strings
urls="$url $urls"
shortnames="$shortname $shortnames"
longnames="$longname $longnames"
done
## extract the base URI
URI=`echo "$1" | sed -e 's/\/[^\/]*$//' -e 's/^\//file:\/\/\//'`
## Find the directory of the first item and go there
DIR=`echo "$1" | sed -e 's/^file:\/\///g'`
DIR=`dirname "$DIR"`
cd $DIR
#Export the environment variables that nautilus sets
export NAUTILUS_SCRIPT_SELECTED_FILE_PATHS=$longnames
export NAUTILUS_SCRIPT_SELECTED_URIS=$urls
export NAUTILUS_SCRIPT_CURRENT_URI=$URI
export NAUTILUS_SCRIPT_WINDOW_GEOMETRY="800x500+10+10"
#Execute the proper script if anything was actually passed to this script
if [ -n "$1" ]
then
"$SCRIPTNAME" $shortnames
fi
==== nautilus-scripts/Varios/SystemConfiguration/pynautilus ====
$ cat nautilus-scripts/Varios/SystemConfiguration/pynautilus
#!/usr/bin/env python
"""
This function extracts Nautilus variables from the environment, splits them on
newlines and puts results in dictionary.
Example:
ala = parse_nautilus_environment()
for tmp in ala['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS']:
print tmp
"""
def parse_nautilus_environment():
import os
result = {
'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' : [],
'NAUTILUS_SCRIPT_SELECTED_URIS' : [],
'NAUTILUS_SCRIPT_CURRENT_URI' : [],
'NAUTILUS_SCRIPT_WINDOW_GEOMETRY' : [] # I wonder if anyone uses it ;)
}
for i in result.keys():
if os.environ.has_key(i):
result[i] = os.environ[i].split(':')
else:
result[i] = []
return result
==== nautilus-scripts/Varios/SystemConfiguration/Query_RPM ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Query_RPM
#!/bin/sh
quoted=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | awk 'BEGIN {
FS = "\n" } { printf "\"%s\" ", $1 }' | sed -e s#\"\"##)
eval "gnorpm -q -p $quoted"
==== nautilus-scripts/Varios/SystemConfiguration/RPM-install-update ====
$ cat nautilus-scripts/Varios/SystemConfiguration/RPM-install-update
#!/bin/bash
#
# Nautilus script -> Install or Update Rpm with gnorpm
#
# Owner : Largey Patrick from Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
#
# Ver: 1.0 Date: 31.03.2002
# Initial release
#
# Dependence : Nautilus (of course)
# Gdialog (Gnome-utils)
# Gnome-Rpms (gnorpms)
#
title="Rpm Installer-Updater"
rpminstaller="What do you want to make ?"
install="install"
update="update"
info="information"
case $LANG in
fr* )
title="Rpm installation ou mise \E0 jour"
rpminstaller="Que voulez-vous faire ?"
install="installation"
update="mise \E0 jour"
info="information";;
esac
filesall=""
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\?/g'`
filesall="$files $filesall"
shift
done
admin=`whoami`
if
rpmchoise=`gdialog --title "$title" --radiolist "$rpminstaller" 260 100 5 "-i" "$install" off "-U" "$update" on "-qp" "$info" off 2>&1`
then
case $rpmchoise in
-i )
if [ $admin = root ]
then
gnorpm -i $fileall&
else
gnorpm-auth -i $filesall&
fi;;
-U )
if [ $admin = root ]
then
gnorpm -U $fileall&
else
gnorpm-auth -U $filesall&
fi;;
-qp )
if [ $admin = root ]
then
gnorpm -qp $fileall&
else
gnorpm-auth -qp $filesall&
fi;;
esac
else
exit 0
fi
==== nautilus-scripts/Varios/SystemConfiguration/RPM-tools ====
$ cat nautilus-scripts/Varios/SystemConfiguration/RPM-tools
#!/bin/bash
#
# Nautilus script -> Install or Update Rpm with gnorpm
#
# Owner : Largey Patrick from Switzerland
# patrick.largey@nazeman.org
# www.nazeman.org
#
# Licence : GNU GPL
#
# Copyright (C) Nazeman
#
# Ver: 1.04
# Remove nodeps option don't work with gnorpm
#
# Ver: 1.03
# Add check if one Rpm is selected or not
#
# Ver: 1.02
# Add spanish translation by Manuel Clos
#
# Ver: 1.01
# Bug fix with user root + add possibilty to install or update with nodeps
#
# Ver: 1.0 Date: 31.03.2002
# Initial release
#
# Dependence : Nautilus (of course)
# Gdialog (Gnome-utils)
# Gnome-Rpms (gnorpms)
#
title="Rpm Installer-Updater"
rpminstaller="What do you want to make ?"
install="install"
update="update"
info="information"
dontrpm="That's not a RPM package !"
case $LANG in
fr* )
title="Rpm installation ou mise \E0 jour"
rpminstaller="Que voulez-vous faire ?"
install="installation"
update="mise \E0 jour"
info="information"
dontrpm="Ce n'est pas un paquet RPM !";;
es* )
title="Instalador-Actualizador de Rpm"
rpminstaller="\BF Qu\E9 desea hacer ?"
install="instalar"
update="actualizar"
info="informaci\F3n";;
esac
filesall=""
testrpm=`file -b "$1" | grep 'RPM'`
while [ $# -gt 0 ]
do
files=`echo "$1" | sed 's/ /\?/g'`
filesall="$files $filesall"
shift
done
admin=`whoami`
if [ "$testrpm" != "" ]
then
if
rpmchoise=`gdialog --title "$title" --radiolist "$rpminstaller" 200 150 9 "-i" "$install" off "-U" "$update" on "-qp" "$info" off 2>&1`
then
case $rpmchoise in
-i )
if [ $admin = root ]
then
gnorpm -i $filesall&
else
gnorpm-auth -i $filesall&
fi;;
-U )
if [ $admin = root ]
then
gnorpm -U $filesall&
else
gnorpm-auth -U $filesall&
fi;;
-qp )
if [ $admin = root ]
then
gnorpm -qp $filesall&
else
gnorpm-auth -qp $filesall&
fi;;
esac
else
exit 0
fi
else
gdialog --title "$title" --msgbox "$dontrpm" 250 100
fi
==== nautilus-scripts/Varios/SystemConfiguration/Set_as_Directory_Icon ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Set_as_Directory_Icon
#!/usr/bin/perl
#
# Nautilus Script:
# Set selected image as the current directory's icon
#
# Owner:
# Barak Korren
# ifireball@yahoo.com
#
# Licence: GNU GPL
# Copyright (C) Barak Korren
#
# Change log:
# Mon, Apr 05, 2004 - Created.
#
# Known Issues:
# Nautilus needs to be restarted for changes to take effect.
# The file set is the icon is arbitarily the last one passed by Nautilus.
# No filetype checking is performed.
#
use XML::LibXML;
sub urify($) {
my $str = shift;
$str =~ s/([\/% ])/sprintf("%%%X", ord($1))/eg;
return $str;
}
sub errorquit($) {
exec "zenity --error --text='${_[0]}'";
exit;
}
$su = $ENV{'NAUTILUS_SCRIPT_SELECTED_URIS'}
or die('This script must be run from Nautilus!');
$cu = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'}
or die('This script must be run from Nautilus!');
($icon) = ($su =~ m/([^\n]*$)/);
($metafile,$dir) = ($cu =~ m/(.*)\/([^\/]+)/);
$metafile = $ENV{'HOME'} . "/.nautilus/metafiles/" . urify($metafile) . ".xml";
if (-e $metafile) {
find mu # If metafile exists, verify we can
# read and write it, then parse it
if( -r $metafile && -w $metafile) {
$mf = XML::LibXML->new()->parse_file($metafile);
$de = $mf->documentElement();
}
else {
errorquit("Can't edit metafile:\n$metafile");
}
}
else {
# If Metafile doesn't exist, make one
$mf = XML::LibXML::Document->new();
$de = $mf->createElement('directory');
$mf->setDocumentElement($mf);
}
# See if we got a
if(@nodes = $de->findnodes("file[\@name=\"$dir\"]")) {
$fe = @nodes[0];
}
else {
# If there isn't an element make it
$fe = $mf->createElement("file");
$fe->setAttribute("name", $dir);
$de->appendChild($fe);
}
# Finally, set the custom_icon attribute
$fe->setAttribute("custom_icon", $icon);
# Now save our work
$mf->toFile($metafile, 0);
==== nautilus-scripts/Varios/SystemConfiguration/Set_as_Wallpaper ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Set_as_Wallpaper
#!/bin/sh
# From Tuomos Kuosmanen on the Nautilus Mailing List
background-properties-capplet --init-session-settings --background-image="`pwd`/$1"
==== nautilus-scripts/Varios/SystemConfiguration/Set_image_as_Wallpaper ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Set_image_as_Wallpaper
#!/bin/bash
###############################################################################
# Display a fullscreen slideshow of the selected files
###############################################################################
#
# AUTHOR: Karl Bowden
#
# CREDITS: Brian Connelly
# that I based this script on.
#
# DESCRIPTION: This script sets the background in Gnome2 the the selected
# filename.
#
# REQUIREMENTS: Nautilus file manager
# Gnome2
# gdialog, which is usually included in the gnome-utils package
#
# INSTALLATION: copy to the ~/.gnome2/nautilus-scripts directory
#
# USAGE: Select the file that you would like to use as your wallpaper
# in Nautilus, right click, go to Scripts, and then select this
# script. You will then be asked to selest how you would like
# the image displayed.
#
# VERSION INFO:
# 0.1 (20020928) - Initial public release
#
# COPYRIGHT: Copyright (C) 2002 Karl Bowden
#
# LICENSE: GNU GPL
#
###############################################################################
WALLPAPER=$(gdialog --title "Wallpaper Options" --radiolist "Picture Options:" 60 100 10 1 Wallpaper on 2 Centered off 3 Scaled off 4 Stretched off 2>&1)
if [ $WALLPAPER = "1" ]; then
gconftool-2 --type=string --set /desktop/gnome/background/picture_options wallpaper
gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
fi
if [ $WALLPAPER = "2" ]; then
gconftool-2 --type=string --set /desktop/gnome/background/picture_options centered
gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
fi
if [ $WALLPAPER = "3" ]; then
gconftool-2 --type=string --set /desktop/gnome/background/picture_options scaled
gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
fi
if [ $WALLPAPER = "4" ]; then
gconftool-2 --type=string --set /desktop/gnome/background/picture_options stretched
gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
fi
==== nautilus-scripts/Varios/SystemConfiguration/Show_Directory_Metafile ====
$ cat nautilus-scripts/Varios/SystemConfiguration/Show_Directory_Metafile
#!/usr/bin/perl
#
# Nautilus Script:
# Show the current directory's XML metafile.
#
# Owner:
# Barak Korren
# ifireball@yahoo.com
#
# Licence: GNU GPL
# Copyright (C) Barak Korren
#
# Dependency:
# zenity, xmllint, xmessage
#
# Change log:
# Mon, Apr 05, 2004 - Created.
#
# Known Issues:
# I'd like to use zentity instead of xmessage, but it doesn't currently
# support showing text from the standard input, too bad gless doesn't seem
# to be shipped with gnome-utils anymore, maybe one can use the builtin
# Nautilus text viewer?
#
sub urlify($) {
my $str = shift;
$str =~ s/([\/% ])/sprintf("%%%X", ord($1))/eg;
return $str;
}
$MFN = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'}
or die('This script must be run from Nautilus!');
$MFN = $ENV{'HOME'} . "/.nautilus/metafiles/" . urlify($MFN) . ".xml";
if ( -r $MFN ) {
exec "xmllint --format $MFN | xmessage -file -";
}
else {
exec "zenity --error --text='Not Found:\n $MFN'";
}
==== nums ====
$ cat nums
1
2
3
==== octais1.sh ====
$ cat octais1.sh
#!/bin/sh
#
# Lista os caracteres entre \0000 e \0377 gerados pelo echo no octal correspondente
# Caso receba a opcao -tn, para n variando de 1 a 9 a listagem serah temporizada
#
tp=0
[ `echo "$1" | sed -n '/^-[tT][1-9]$/p'` ] && tp=`expr substr $1 3 1 \* 20`
[ $tp -eq 0 -a $# -gt 0 ] &&
{
echo "Uso $0 [-tn] onde n \0351 um temporizador entre 1 e 9"
exit 1
}
for i in 0 1 2 3
do
for j in 0 1 2 3 4 5 6 7
do
for k in 0 1 2 3 4 5 6 7
do
echo "0$i$j$k=\0$i$j$k\t\c"
tp1=0
while [ $tp1 -lt $tp ]
do
tp1=`expr $tp1 + 1`
done
[ $k -eq 7 ] && echo
done
done
done
==== octais2.sh ====
$ cat octais2.sh
#! /bin/bash
#
# Lista os caracteres entre \0000 e \0377 gerados pelo echo no octal correspondente
# Caso receba a opcao -tn, para n variando de 1 a 9 a listagem serah temporizada
#
loop1='0 1 2 3'
loop2='0 1 2 3 4 5 6 7'
set -A array 0 1 2 3 4 5 6 7
echo " ${array[0]} ${array[1]} ${array[2]} ${array[3]}\
${array[4]} ${array[5]} ${array[6]} ${array[7]} "
echo
for i in $loop1
do
for j in $loop2
do
echo "$i$j \0$i$j${array[0]} \0$i$j${array[1]}\
\0$i$j${array[2]} \0$i$j${array[3]} \0$i$j${array[4]}\
\0$i$j${array[5]} \0$i$j${array[6]} \0$i$j${array[7]}"
done
done
echo
echo " ${array[0]} ${array[1]} ${array[2]} ${array[3]}\
${array[4]} ${array[5]} ${array[6]} ${array[7]} "
echo
==== param1 ====
$ cat param1
echo $1
echo $2
echo $11
==== param2 ====
$ cat param2
echo $0
echo $2
echo ${11}
==== param3 ====
$ cat param3
echo O programa $0 Recebeu $# Parametros
echo $1
echo $2
echo ${11}
==== param4 ====
$ cat param4
echo O Programa $0 Recebeu $# Parametros Listados Abaixo:
echo $*
==== param5 ====
$ cat param5
echo O programa $0 Recebeu $# Parametros
echo $1
echo $2
shift 10
echo $1
==== param6 ====
$ cat param6
echo O programa $0 Recebeu $# Parametros
echo -n "Que sao: "
for i
do
echo -n "$i "
done
==== param7 ====
$ cat param7
#!/bin/bash
# Programa para testar passagem de parametros (3a. Versao)
echo O programa $(basename $0) recebeu $# parametros
echo "11o. parm (errado)-> $11"
echo "10o. parm (certo) ${10}"
echo "11o. parm (certo) ${11}"
shift
echo "2o. parm -> $1"
shift 2
echo "4o. Parm -> $1"
==== passwd.tmp ====
$ cat passwd.tmp
bin:x:2:2:bin:/bin:/bin/sh
pulse:x:109:114:PulseAudio daemon,,,:/var/run/pulse:/bin/false
rtkit:x:110:117:RealtimeKit,,,:/proc:/bin/false
saned:x:111:118::/home/saned:/bin/false
hplip:x:112:7:HPLIP system user,,,:/var/run/hplip:/bin/false
gdm:x:113:120:Gnome Display Manager:/var/lib/gdm:/bin/false
julio:x:1000:1000:Julio Neves,,,:/home/julio:/bin/bash
postfix:x:114:123::/var/spool/postfix:/bin/false
==== pedi ====
$ cat pedi
#
# Testa a resposta a um pedido. Deve ser (S)im ou (N)ao - Versao 3
#
if test $# = 0
then
echo Faltou informar a resposta
exit 1
fi
resp=$1
if test "$resp" = N
then
echo Ela nao deixa...
elif test "$resp" = S
then
echo Oba, ela deixou!!!
else
echo Acho que ela esta na duvida.
fi
==== pp ====
$ cat pp
#
# Pesquisa Pessoa no Catalogo Telefonico - versao 2
#
grep "$1" telefones
==== pp.awk ====
$ cat pp.awk
awk '/'$1'/' telefones
==== quebralingua.txt ====
$ cat quebralingua.txt
Eu vi um velho com um fole velho nas costas.
Tanto fede o fole do velho,
quanto o velho do fole fede.
==== quequeisso ====
$ cat quequeisso
ATENCAO, O TEXTO ABAIXO NAO EH TREINAMENTO,
EH UMA LAVAGEM CEREBRAL!!!
O Shell alem de analisar cada dado entrado a partir do prompt do UNIX,
interfaceando com os usuarios, tem tambem as seguintes atribuicoes:
Interpretador de comandos;
Controle do ambiente UNIX;
Redirecionamento de entrada e saida;
Substituicao de nomes de arquivos;
Concatenacao de pipe;
Execucao de programas;
Poderosa linguagem de programacao.
==== quero ====
$ cat quero
quero-quero
quero quero
come-come
bate-bate
batebate
rebate-bate
rebate-bateria
queroquero
comecome
bate-bateria
hoje-joia
come come
bole--bole
come come
==== rem ====
$ cat rem
#
# Remove Pessoas do Arquivo de Telefones
#
grep -v "$1" telefones > /tmp/$$
mv /tmp/$$ telefones
==== restaura ====
$ cat restaura
#!/bin/bash
#
# Restaura arquivos deletados vi erreeme
#
if [ $# -eq 0 ]
then
echo "Uso: $0
exit 1
fi
Dir=`tail -1 /tmp/$LOGNAME/$1`
grep -v $Dir /tmp/$LOGNAME/$1 > $Dir/$1
rm /tmp/$LOGNAME/$1
==== rotinas.sh ====
$ cat rotinas.sh
Maquina=""
SN=""
OL=""
function Erro
{
Len=`expr length "$1"`
C=`expr "(" 80 - "$Len" ")" / 2`
tput cup 21 $C
echo "$1\07\c"
read a < /dev/tty
tput cup 21 1
echo " "
return
}
function Pergunta
{
DefVal=`echo "$2" | tr "[a-z]" "[A-Z]"`
OthVal=`echo "$3" | tr "[a-z]" "[A-Z]"`
Quest=`echo "${1}? ${DefVal}//"`
Len=`expr length "$Quest"`
Col=`expr \( \`tput cols\` - "$Len" ")" / 2`
tput cup `expr \`tput lines\` - 2` $Col
echo "$Quest\07\c"
read SN < /dev/tty
SN=${SN:-"$DefVal"}
SN=`echo $SN | tr "[a-z]" "[A-Z]"`
if [ "$SN" != "$OthVal" ]
then
SN="$DefVal"
fi
tput cup `expr \`tput lines\` - 2` 1
tput el
return
}
#!/bin/bash
#
#==========================================================
# Recebe uma qtd de dias como parametro, e o transforma em
# uma data, que significa 1/1/1980 + parametro recebido.
# Obs. Para executar este programa sob o sh, trocar por
# $((..)) por expr
#==========================================================
# Leia: Linux - Programacao Shell ISBN: 85-7452-048-9
# Autor: Julio Cezar Neves
#==========================================================
#
Num=$(($1 - 1))
AFim=$((1980 + (Num / 365)))
DFim=$((Num % 365 - Num / 1460))
MFim=1
for i in 31 28 31 30 31 30 31 31 30 31 30 31
do
[ $DFim -lt $i ] && break
DFim=$((DFim - i))
MFim=$((MFim + 1))
done
[ $DFim -eq 0 ] &&
{
DFim=29
MFim=2
}
[ $DFim -le 9 ] && echo "0$DFim/\c" || echo "$DFim/\c"
[ $MFim -le 9 ] && echo "0$MFim/\c" || echo "$MFim/\c"
echo $AFim
#!/bin/bash
#
#======================================================================
# Calcula qtd dias entre uma data passada como parametro e 01/01/1980.
# Se nao for passado nenhum parametro a data de hoje sera assumida.
# Obs. Para executar este programa sob o sh, trocar os $((..)) por expr
#======================================================================
# Leia: Linux - Programacao Shell ISBN: 85-7452-048-9
# Autor: Julio Cezar Neves
#======================================================================
#
if [ $1 ]
then
DFim=`echo $1 | cut -f1 -d"/"`
MFim=`echo $1 | cut -f2 -d"/"`
AFim=`echo $1 | cut -f3 -d"/"`
else
DFim=`date +%d`
MFim=`date +%m`
AFim=`date +%Y`
fi
TotDias=$((1 + 365 * (AFim - 1980) + (AFim - 1980) / 4))
[ $((AFim % 4)) = 0 -a $MFim -le 2 ] && TotDias=$((TotDias - 1))
for i in `echo "31 28 31 30 31 30 31 31 30 31 30 31" | cut -f-$((MFim - 1)) -d" " 2> /dev/null`
do
TotDias=$((TotDias + $i))
done
echo $((TotDias + DFim))
Limpa ( )
{
tput cup 21 1
echo " "
return
}
Mostra ( )
{
Mostra=$*
Limpa
Len=`expr length "$Mostra"`
Col=`expr "(" 80 - "$Len" ")" / 2`
tput cup 21 $Col
echo "$Mostra"
}
function Cab
{
clear
echo "
+------------+------------+--------------------------------------------+
| | | |
| DATAPREV | TRANSFTP | Producao RJ (821)2347 |
| | | Suporte (821)2338 SP (811)6200 |
+------------+------------+--------------------------------------------+"
}
function Div # Faz divisao de inteiros dando resultado com $3 decimais
{
Divid=$1
Divis=$2
Decim=$3
Resp=`expr $Divid / $Divis`,
while [ "$Decim" -gt 0 ]
do
Divid=`expr $Divid % $Divis \* 10`
Resp=$Resp`expr $Divid / $Divis`
Decim=`expr $Decim - 1`
done
return # Quociente editado esta em Resp
}
function ChecaPW
{
Lin=$(($1\*4+7))
if [ "$2" -eq 1 ]
then
Site=RJ
Maquina=durjcv01
else
Site=SP
Maquina=duspmv01
fi
j=1
while true
do
tput cup $Lin $Cwr
echo "Login Name em $Site ($LOGNAME): "
tput cup $Lin $Cre
read User
User=${User:-"$LOGNAME"}
tput cup $Lin $Cre
echo $User
tput cup $(($Lin+2)) $Cwr
echo "Entre com Password em $Site:"
tput cup $(($Lin+2)) $Cre
stty -echo
read PW
stty echo
if [ -z "$PW" ]
then
Pergunta "Deseja continuar" S N
if [ "$SN" = N ]
then
exit
fi
continue
fi
ftp -ivn $Maquina << fimftp > "/tmp/$$" ## So para testar a senha...
user "$User" "$PW"
quit
fimftp
if [ `grep -c "^530 " "/tmp/$$"` -ne 0 ]
then
j=`expr $j + 1`
if [ "$j" -eq 4 ] ## Se em 4 tentativas nao acertar; BYE BYE...
then
Erro "Tentativa de violacao. Programa descontinuado."
rm /tmp/"$$"
exit
fi
Erro "Senha nao confere. Tente outra vez."
continue
fi
break
done
}
function LeMaq
{
Lin=$1
Col=$2
if [ "$#" -eq 3 ]
then
MaqDef=$3
fi
while true
do
tput cup $Lin $Col
echo " "
tput cup $Lin $Col
read Maquina
if [ "$#" -eq 3 ]
then
Maquina=${Maquina:-"$MaqDef"}
fi
if [ -z "$Maquina" ]
then
SN "Deseja Abandonar" S N
if [ "$SN" = N ]
then
continue
fi
exit
fi
if [ `fgrep -c "$Maquina" /etc/hosts` -eq 0 ]
then
Erro "Nao existe regional com maquina com este nome"
continue
fi
return
done
}
function LeOL
{
Col=$1
Lin=$2
OLs="02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 28"
while true
do
tput cup $Lin $Col
echo " "
tput cup $Lin $Col
read OL
if [ -z "$OL" ]
then
SN "Deseja Abandonar" S N
if [ "$SN" = N ]
then
continue
fi
exit
fi
if [ `echo "$Maquina" | fgrep -c "$OLs"` -eq 0 ]
then
Erro "Nao existe OL com este numero"
continue
fi
return
done
}
==== saldo.awk ====
$ cat saldo.awk
#
# Calcula Saldo em Conta Corrente
#
awk '
FILENAME == "creditos" { Saldo[$1] += $2 }
FILENAME == "debitos" { Saldo[$1] -= $2 }
END { for (Nome in Saldo)
print Nome, Saldo [Nome]
}' creditos debitos
==== salva_tela.sh ====
$ cat salva_tela.sh
#!/bin/bash
seq 2000 | xargs # Sujando a tela
Lin=$(($(tput lines) / 2)) # Calculando linha e coluna centrais da tela
Col=$(($(tput cols) / 2))
tput cup $Lin; tput el; tput setf 1 # Posicionando, apagando a linha central e colorindo
echo "Em 10 segundos essa tela será fotografada e se apagará"
tput civis # Cursor invisível para melhorar apresentação
for ((i=10; i!=0; i--))
{
tput cup $Lin $Col; tput el # Posiciona no centro da tela e limpa núm anterior
echo $i
sleep 1
}
tput smcup # Tirando uma foto da tela
clear # Poderia ter usado tput reset
tput cup $Lin
echo "Dentro de 10 segundos a tela inicial será recuperada"
for ((; i<10; i++))
{
tput cup $Lin $Col # Posicionou no centro da tela
echo $i
sleep 1
}
tput rmcup # Restaurou a foto
tput cvvis;tput setf 9 # Restaurou o cursor e cor
==== talogado ====
$ cat talogado
#
# Verifica se determinado usuario esta "logado" - versao 2
#
if who | grep $1 > /dev/null
then
echo $1 esta logado
else
echo $1 nao esta logado
fi
==== tavazio ====
$ cat tavazio
==== tecla.sh ====
$ cat tecla.sh
getc ()
{
stty raw
eval $1="`dd bs=1 count=1 2>/dev/null | tr '\015' '\012'`"
stty cooked
}
echo "Digite uma opcao: \c"
getc anychar
echo \\n\\n\\n$anychar\\n\\n\\n
==== telef ====
$ cat telef
Ciro
Ney
Enio
Claudia
Paula
Ney
==== telefones ====
$ cat telefones
Ciro Grippi (021)555-1234
Claudia Marcia (021)555-2112
Enio Cardoso (023)232-3423
Juliana Duarte (024)622-2876
Luiz Carlos (021)767-2124
Ney Garrafas (021)988-3398
Ney Gerhardt (024)543-4321
Paula Duarte (011)449-0219
==== teles ====
$ cat teles
#!/bin/bash
#
# Menu do cadastro de telefones - versao 3
#
if [ "$#" -ne 0 ]
then
pp "$*"
exit
fi
OK=
until [ "$OK" ]
do
read Opcao?"
Opcao Acao
===== ====
1 Procurar Alguem
2 Adicionar Alguem ao Caderno de Telefones
3 Remover Alguem do Cadastro de Telefones
4 Listagem do Caderno de Telefones
Escolha Uma Das Opcoes Acima (1-4): "
echo "\n"
OK=1
case "$Opcao"
in
1) read Nome?" Entre com o nome a pesquisar: "
pp "$Nome"
;;
2) read Nome?" Nome a ser adicionado: "
read Telef?" Telefone de $Nome: "
add "$Nome" "$Telef"
;;
3) read Nome?" Nome a ser removido: "
rem "$Nome"
;;
4) lt
;;
*) echo "Soh sao validas opcoes entre 1 e 4"
OK=
;;
esac
done
exit
==== testa_branch.sh ====
$ cat testa_branch.sh
#!/bin/sh
sed -n "
# Se linha vazia, vá pesquisar cadeia
/^$/ b PesqCad
# Senão, acrescenta a linha ao hold buffer
H
# Fim de arquivo também é fim de parágrafo
$ b PesqCad
# Vai para o fim para saltar PesqCad
b
# É aqui que vamos procurar a cadeia no parágrafo
:PesqCad
# Manda todo o parágrafo para o pattern space
x
# Procura a cadeia, se achar imprime
/$1/ p
" $2
==== testa_sed ====
$ cat testa_sed
1 # Esta linha nao serah analisada
# A partir daqui, existem linhas vazias
#+ linhas somente com espacos em branco
#+ e linhas com
2 # Esta eh uma linha que deve ser mantida
3 # Esta tb deve ser mantida
# Isto eh um
4 # Essa tb serah mantida
==== testchar ====
$ cat testchar
#
# Testa qual o tipo de um caracter recebido por parametro
#
##### Teste da Quantidade de Parametros #####
erro=0
if [ "$#" -ne 1 ]
then
echo "Uso: $(basename $0) caractere"
erro=1
fi
##### Testa se o 1o. parametro tem o tamanho de um caracter #####
case $1 in
?) ;;
*) echo "Erro -> Parametro passado deveria ter um caracter"
erro=2
;;
esac
##### Se houve erro o programa termina, passando o codigo do erro #####
if [ "$erro" -ne 0 ]
then
exit $erro
fi
case $1 in
[a-z]) echo Letra Minuscula
;;
[A-Z]) echo Letra Maiuscula
;;
[0-9]) echo Numero
;;
*) echo Caracter Especial
;;
esac
exit 0
==== teste ====
$ cat teste
echo $$
==== testsex ====
$ cat testsex
clear
sexo=$1
if [ "$sexo" -lt 1 -o "(" "$sexo" -gt 2 ")" ]
then
tput cup 21 20
tput smso
echo "Nao sabia que eramos colegas, meu bem!!"
sleep 5
tput rmso
tput reset
exit 1
fi
tput bold
tput cup 10 35
if [ "$sexo" -eq 1 ]
then
echo sexo masculino
else
echo sexo feminino
fi
sleep 5
tput rmso
tput reset
exit
==== TiraBranco.sh ====
$ cat TiraBranco.sh
#!/bin/bash
# Renomeia arquivos com espaços nem branco
#+ no nome, trocando-os por sublinhado (_).
Erro=0
for Arq in *' '*
do
[ -f ${Arq// /_} ] && {
echo $Arq não foi renomeado
Erro=1
continue
}
mv "$Arq" "${Arq// /_}"
done 2> /dev/null
exit $Erro
==== toca ====
$ cat toca
Flg=
for i
do
case $i in
-c) Flg=N
;;
*) if [ -f $i ]
then
ln $i lixo$$
ls -l lixo$$
rm lixo$$
elif [ $Flg ] # Verdadeiro se nao nulo
then
echo \'$i\' nao existe
else
>$i # Cria o arquivo passado com tamanho = zero
fi
;;
esac
done
==== tputcup ====
$ cat tputcup
tput cup 3 6
echo ".<-"
tput cup 2 10
echo "/"
tput cup 1 12
echo "/"
tput cup 0 14
echo "_________ Este eh o ponto (3, 6)"
==== tr ====
$ cat tr
Alpha
==== trocacase.sh ====
$ cat trocacase.sh
#!/bin/bash
# Se o nome do arquivo tiver pelo menos uma
#+ letra maiúscula, troca-a para minúscula
for Arq in *[A-Z]*
do
if [ -f "${Arq,,}" ]
then
echo ${Arq,,} já existe
else
mv "$Arq" "${Arq,,}"
fi
done
==== tst_exec ====
$ cat tst_exec
exec 1>saida_unica 2>&1
ls $1 || echo O arquivo $1 não existe >&2
echo Fim do programa
==== tstmatr ====
$ cat tstmatr
while true
do
clear
tput cup 10 15
echo "Entre com sua matricula: \c"
read Matric
if [ ! "$Matric" ]
then
tput cup 12 15
echo "Deseja abandonar? (N/s) \c"
read sn
if [ "$sn" = S -o "(" "$sn" = s ")" ]
then
exit
fi
continue
fi
if expr $Matric + 1 1> /dev/null 2>&1
then
break
else
tput cup 12 15
echo "Matricula Nao Numerica"
read a
continue
fi
done
==== upperconv.sh ====
$ cat upperconv.sh
#!/bin/bash
# upperconv.sh
# Converte arquivo em maiúscula dando a saída em outro arquivo
if [ ! -r "$1" ] # Posso ler arq de entrada?
then
echo Informe arquivo de entrada com direito de leitura
echo Uso: "$0
exit 1
fi
if [ ! -w "$2" ]
then
echo Informe arquivo de saída com direito de gravação
echo Uso: $0 "
exit 2
fi
exec 4<&0 # Salva stdin no fd 4
exec < $1 # Associa stdin ao arq. em $1
exec 7>&1 # Salva stdout no fd 7
exec > $2 # Associa stdout ao arq. em $2
# -----------------------------------------------
cat - | tr a-z A-Z # Converte par maiúscula
# ^^^^^ # O hifem sempre representa stdin.
# ^^^^^^^^^^ # Saída do tr para stdout.
# -----------------------------------------------
exec 1>&7 7>&- # Restaura stout.
exec 0<&4 4<&- # Restaura stdin.
# Agora volta tudo ao normal: stdin é o teclado e
# e stdout é a tela. Veja:
echo Arquivo \"$1\" foi escrito para \"$2\" em maiúsculas
==== usus ====
$ cat usus
^bin:
^irc:
^root:
^sys:
^uucp:
==== variando ====
$ cat variando
echo a=$a:
a=xx
echo a=$a:
b=`variando1`
echo b=$b
==== variando1 ====
$ cat variando1
echo a=$a:
==== VelEcon ====
$ cat VelEcon
awk 'BEGIN { MinCons=99999 }
{
if ( $2 > MaxVel )
{
CarVel=$1
MaxVel=$2
}
if ( $4 < MinCons )
{
CarEcon=$1
MinCons=$4
}
}
END {
print "O",CarVel,"desenvolve",MaxVel,\
"km e\nO",CarEcon,"faz",MinCons,"km/l\n"
}' carros
==== velha.sh ====
$ cat velha.sh
#!/bin/bash
#
#######################################################
# JOGO DA VELHA #
# DUVIDO QUE VOCE CONSIGA GANHAR! #
#-----------------------------------------------------#
# TIC TAC TOE #
# I WON'T GIVE YOU A CHANCE. YOU'LL NEVER WIN! #
#######################################################
# #
# Leia: Programacao Shell - Linux #
# Autor: Julio Cezar Neves #
# Editora: Brasport #
# ISBN: 85-7452-076-4 #
# #
#######################################################
# Para qualquer duvida ou esclarecimento sobre este #
# programa estou as ordens em julio.neves@bigfoot.com #
#-----------------------------------------------------#
# Any doubt about this program you can find me at #
# julio.neves@bigfoot.com #
#######################################################
# Se voce estiver sob o bash, troque a 1a. linha por #
# #!/bin/bash #
#-----------------------------------------------------#
# If you are running bash change the 1st. line for #
# #!/bin/bash #
#######################################################
# Este foi um meio divertido que encontrei para #
# testar a compatibilidade no uso de arrays entre o #
# bash e o ksh. Se alguem quiser desenvolver a rotina #
# em que o adversario comeca jogando, sinta-se a #
# vontade, porem nao esqueca de mandar-me o modulo #
# para incorpora-lo ao meu. #
#-----------------------------------------------------#
# This program was developed as a funny way to test #
# the compatibility between arrays in ksh and bash. #
# Feel free for develop the module that the opponent #
# start playing, but don't forget to send me the new #
# routine because I'll attach it at this one. #
#######################################################
#
Ganhei=0
Empate=0
Bold=`tput bold`
OBold=`tput sgr0`
Cols=`tput cols`
if [ $Cols -lt 80 -o `tput lines` -lt 25 ]
then
clear
echo "O tamanho minimo da janela deve ser 25 linhas e 80 colunas"
exit 2
read lixo
fi
Col0=`expr \( $Cols - 46 \) / 2`
Eng=`echo "To play in english use: $Bold\`basename $0\`$OBold -e (default language is portuguese)"`
# Ingles ou Portugues? English or Portuguese?
if [ "$1" = -e ]
then
StrIni[1]=" 1 2 3"
StrIni[2]="1 | | +---------+----------+"
StrIni[3]=" ---+---+--- | Ties | Wins |"
StrIni[4]="2 | | +---------+----------+"
StrIni[5]=" ---+---+--- | | |"
StrIni[6]="3 | | +---------+----------+"
StrGan="I W O N !!!"
StrEmp="T I E"
StrLe="Now it's our time to play (RowColumn):"
StrEr1="At this position already has a -> "
StrEr2="Write row and column together. I.E. 13 means row 1 and column 3"
StrFim="Do you want to continue?"
else
StrIni[1]=" 1 2 3"
StrIni[2]="1 | | +---------+----------+"
StrIni[3]=" ---+---+--- | Empates | Vitorias |"
StrIni[4]="2 | | +---------+----------+"
StrIni[5]=" ---+---+--- | | |"
StrIni[6]="3 | | +---------+----------+"
StrGan="G A N H E I !!!"
StrEmp="E M P A T E"
StrLe="Informe a sua jogada (LinhaColuna):"
StrEr1="Nesta posicao ja existe um -> "
StrEr2="Informe Linha e Coluna juntos. Ex: 13 = Linha 1 e Coluna 3"
StrFim="Deseja continuar?"
fi
Escrever ()
{
ColIni=`expr \( $Cols - length "$2" \) / 2`
tput cup $1 $ColIni
echo "$2"
}
Iniciar ()
{
Jogo=
for i in 1 2 3
do
for j in 1 2 3
do
P[$i$j]=
done
done
clear
for i in 1 2 3 4 5 6
do
tput cup `expr 11 + $i` $Col0
echo "${StrIni[i]}"
done
Seg=`date "+%S"`
case `expr $Seg % 5` in
0) Jogo=11 ; Saida=1 ;;
1) Jogo=13 ; Saida=2 ;;
2) Jogo=31 ; Saida=3 ;;
3) Jogo=33 ; Saida=4 ;;
*) Jogo=22 ; Saida=5 ;;
esac
tput cup 16 `expr $Col0 + 29`
echo $Bold$Empate
tput cup 16 `expr $Col0 + 40`
echo $Ganhei$OBold
}
Jogar ()
{
P[$1]=$2
Lin=`echo $1 | cut -c1`
Col=`echo $1 | cut -c2`
Lin=`expr \( $Lin - 1 \) \* 2 + 13`
Col=`expr \( $Col - 1 \) \* 4 + 3 + $Col0`
tput cup $Lin $Col
echo $2
}
Placar ()
{
tput bold
if [ $1 = E ]
then
Empate=$((Empate+1))
tput cup 22 $Col0
echo "$StrEmp"
tput cup 16 `expr $Col0 + 29` # Escrevendo Placar
echo $Empate
else
Ganhei=$((Ganhei+1))
tput cup 22 $Col0
echo "$StrGan"
tput cup 16 `expr $Col0 + 40` # Escrevendo Placar
echo $Ganhei
case $2 in
L) for j in 1 2 3
do
Jogar $i$j X
done
;;
C) for j in 1 2 3
do
Jogar $j$i X
done
;;
D1) for i in 11 22 33
do
Jogar $i X
done
;;
*) for i in 13 22 31
do
Jogar $i X
done
esac
fi
tput sgr0
}
# Cuidado com o chefe! WARNING! The boss is near you!
trap "clear ; exit" 0 2 3
# Jogando Playing
while true
do
Iniciar
if [ "$1" != "-e" ]
then
# tput cup 3 23
Escrever 3 "$Eng"
fi
Jogar $Jogo X
Vez=0
while true
do
if [ $Vez -eq 4 ]
then
Placar E
break
fi
tput cup 21 $Col0
echo "$StrLe"
tput cup 21 `expr $Col0 + 1 + length "$StrLe"`
tput el
tput cup 21 `expr $Col0 + 1 + length "$StrLe"`
read Jogo
case $Jogo in
[1-3][1-3]) if [ ${P[$Jogo]} ]
then
tput cup 22 $Col0
echo -n "$Bold$StrEr1${P[$Jogo]} <-$OBold"
read Jogo
tput cup 22 $ColIni
tput el
tput cup 21 `expr $Col0 + 1 + length "$StrLe"`
tput el
continue
fi
Jogar $Jogo O
Vez=$((Vez+1))
;;
*) tput cup 22 $Col0
echo -n "$Bold$StrEr2$OBold"
read Jogo
tput cup 22 $Col0
tput el
tput cup 21 `expr $Col0 + 1 + length "$StrLe"`
tput el
continue
esac
for i in 1 2 3
do
LX[i]=0 ; CX[i]=0 ; LO[i]=0 ; CO[i]=0 ; DX[i]=0 ; DO[i]=0
done
for i in 1 2 3
do
for j in 1 2 3
do
[ "${P[$i$j]}" = X ] && LX[i]=$((${LX[$i]}+1))
[ "${P[$i$j]}" = O ] && LO[i]=$((${LO[$i]}+1))
[ "${P[$j$i]}" = X ] && CX[i]=$((${CX[$i]}+1))
[ "${P[$j$i]}" = O ] && CO[i]=$((${CO[$i]}+1))
done
done
for i in 11 22 33
do
[ "${P[$i]}" = X ] && DX[1]=$((${DX[1]}+1))
[ "${P[$i]}" = O ] && DO[1]=$((${DO[1]}+1))
done
for i in 13 22 31
do
[ "${P[$i]}" = X ] && DX[2]=$((${DX[2]}+1))
[ "${P[$i]}" = O ] && DO[2]=$((${DO[2]}+1))
done
# Pra ganhar I wanna win!
for i in 1 2 3
do
LAlinhadas[i]=$((${LX[i]}-${LO[i]}))
CAlinhadas[i]=$((${CX[i]}-${CO[i]}))
DAlinhadas[i]=$((${DX[i]}-${DO[i]}))
if [ ${LAlinhadas[i]} -eq 2 ]
then
for j in 1 2 3
do
[ ${P[$i$j]} ] && continue
Jogo=$i$j
Jogar $Jogo X
Placar G L
break 3
done
fi
if [ ${CAlinhadas[i]} -eq 2 ]
then
for j in 1 2 3
do
[ ${P[$j$i]} ] && continue
Jogo=$j$i
Jogar $Jogo X
Placar G C
break 3
done
fi
done
if [ ${DAlinhadas[1]} -eq 2 ]
then
for i in 11 22 33
do
[ ${P[$i]} ] && continue
Jogo=$i
Jogar $Jogo X
Placar G D1
break 2
done
fi
if [ ${DAlinhadas[2]} -eq 2 ]
then
for i in 13 22 31
do
[ ${P[$i]} ] && continue
Jogo=$i
Jogar $Jogo X
Placar G D2
break 2
done
fi
# Pra nao perder I don't wanna lose
for i in 1 2 3
do
if [ ${LAlinhadas[i]} -eq -2 ]
then
for j in 1 2 3
do
[ ${P[$i$j]} ] && continue
Jogo=$i$j
Jogar $Jogo X
continue 3
done
fi
if [ ${CAlinhadas[i]} -eq -2 ]
then
for j in 1 2 3
do
[ ${P[$j$i]} ] && continue
Jogo=$j$i
Jogar $Jogo X
continue 3
done
fi
done
if [ ${DAlinhadas[1]} -eq -2 ]
then
for i in 11 22 33
do
[ ${P[$i]} ] && continue
Jogo=$i
Jogar $Jogo X
continue 2
done
fi
if [ ${DAlinhadas[2]} -eq -2 ]
then
for i in 13 22 31
do
[ ${P[$i]} ] && continue
Jogo=$i
Jogar $Jogo X
continue 2
done
fi
# Ao ataque! Let's attack!
case $Vez in
1) case $Saida in
1) [ ${P[33]} ] && Jogo=13 || Jogo=33 ;;
2) [ ${P[31]} ] && Jogo=33 || Jogo=31 ;;
3) [ ${P[13]} ] && Jogo=11 || Jogo=13 ;;
4) [ ${P[11]} ] && Jogo=31 || Jogo=11 ;;
*) if [ ${P[11]} ]
then
Jogo=33
elif [ ${P[33]} ]
then
Jogo=11
elif [ ${P[13]} ]
then
Jogo=31
else
Jogo=13
fi
esac ;;
*) [ $P{[22]} ] &&
{
Jogo=
for i in 1 3
do
for j in 1 3
do
[ ${P[$i$j]} ] &&
{
[ ${P[$j$i]} ] && continue ||
{
Jogo=$j$i
break 2
}
} ||
{
Jogo=$i$j
break 2
}
done
done
[ "$Jogo" ] &&
{
Jogar $Jogo X
continue
}
for i in 1 2 3
do
for j in 1 2 3
do
[ "${P[$i$j]}" ] && continue
Jogo=$i$j
break 2
done
done
} || Jogo=22
esac
Jogar $Jogo X
done
tput cup 23 $Col0
echo "$StrFim"
tput cup 23 `expr $Col0 + length "$StrFim" + 1`
read a
[ `echo $a | tr n N` = N ] && exit
done
==== vira ====
$ cat vira
#
# vira - vi resguardando arquivo anterior
# == = =
if [ "$#" -ne 1 ]
then
echo "Erro -> Uso: $(basename $0)
exit 1
fi
Arq=$1
if [ ! -f "$Arq" ]
then
vi $Arq
exit 0
fi
if [ ! -w "$Arq" ]
then
echo "Voce nao tem direito de gravacao em $Arq"
exit 2
fi
cp -f $Arq $Arq~
vi $Arq
exit 0