Livra-TE
Menu
  • Início
  • Blog
  • Treinamentos In-Company
    • Livros dos Instrutores
    • Outros Treinamentos
  • Sobre
    • Bacula Backup Software Livre
    • Testimonium Certificações
    • Log in
  • Início
  • Blog
  • Treinamentos In-Company
    • Livros dos Instrutores
    • Outros Treinamentos
  • Sobre
    • Bacula Backup Software Livre
    • Testimonium Certificações
    • Log in

Exercícios e Exemplos do Livro


By admin | November 6, 2014 | Category shell

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 em ArqOLs
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 para prosseguir ou X para terminar...\c"
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 para terminar...\c"
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;i0)) && ((caule<6)) && ((caule>0)); then
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 .tar.gz as default
# 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

#!/usr/bin/perl
# $Revision: 1.1 $
# Luis Mondesi 2002-01-17
#
# 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

# body=
# p=

# table=

# td= # 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
#

# standard modules
use strict;
use vars qw( $VERSION @INC );
use Config;

use Getopt::Long;
Getopt::Long::Configure('bundling');

use File::Copy;
use File::Find; # find();
use File::Basename; # basename();

# for progressbar
use FileHandle;

# non-standard modules:
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

# borrowed ideas from UDPM.pm for the progressbar.
# 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";

# end of loading needed modules

my $VERSION="1.4";

$|++; # disable buffer (autoflush)

my $USAGE = "
pixdir2html.pl [-n|--nomenu]
[-N|--noindex]
[-f|--force]
[-M|--menuonly]
[-E|--extension] (php)
[-t|--thumbsonly]
[-D|--directory] (.)
[-l|--menulinks]
[-c|--cut-dirs]
[-h|--help]

force - creates a .pixdir2htmlrc in every subdir overriding
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

e.g.
cd /path/to/picture_directory
pixdir2html --extension='html'

is the same as:
pixdir2html -E html

";

# Get Nautilus current working directory, if under Natilus:

my $nautilus_root = "";

if ( exists $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'}
&& $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 $ROOT_DIRECTORY= ( -d $nautilus_root ) ? $nautilus_root : ".";
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

# list directories that should be skipped here
# 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;

# dont worry if you don't have a log rotation facility...
# just leave it as is
my $SAVELOG = "/usr/bin/savelog";

###Nothing below this line should need to be configured.###
#**************************************************************#

my @pixdir = (); # for menu
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 $tty = qx/tty/; # this returns text from system("tty")
my $MODE = "text";
my $DIA = "";

# xdialog is a better implementation than gdialog
# 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

# make sure DIA is set or exit abnormally
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;
}
}

# get options
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
);

die $USAGE if $HELP;

my $FILE_NAME="index";
my $MENU_NAME="menu";
my $menu_str="";

my $LOGFILE = new FileHandle;

my $THUMBNAILSDIR="$ROOT_DIRECTORY/$THUMBNAIL";
my $HTMLSDIR="$ROOT_DIRECTORY/$HTMLDIR";

warn << "__EOF__"; Perl pixdir2html v$VERSION (Luis Mondesi / LatinoMixed.com)
(running with Perl $] on $Config{'archname'}) \n \n
__EOF__

main();

#-------------------------------------------------#
# FUNCTIONS #
#-------------------------------------------------#
sub main {

$LOGFILE->open("> $LOG");
$LOGFILE->autoflush(1);

# for now --clear is the same for all dialogs:
# ( $MODE eq "x" ) ? " --clear ":
my $ARGS = " --clear ";

$GAUGE->open("| $DIA $ARGS --backtitle 'Picture Directory to HTML'
--title 'Picture Progress' --gauge 'Thumbnails Creation' 8 70 0 2>&1");
$GAUGE->autoflush(1);

# which progressbar are we using?
print $LOGFILE ("Mode $MODE\n");

# are we creating a menu file only?
if ( $MENUONLY > 0 ) {
print $LOGFILE ("= Creating menu file\n");
menu_file();
return 0;
}

print $LOGFILE "= Start directory $ROOT_DIRECTORY \n";

if ( ! -f "$ROOT_DIRECTORY/$CONFIG_FILE" )
{
print $LOGFILE ( "Missing main $CONFIG_FILE. Creating one for you
\n");
init_config($ROOT_DIRECTORY,"true");
}

# get menu string
# 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();
}

# make all thumbnails and indices
mkthumb($ROOT_DIRECTORY,$menu_str);

if ( $THUMBSONLY > 0 ) {
# this is a quick "dirty" way of getting only
# thumbnails and their respetive index.html files
return 0;
}

# make all supporting HTML files
thumb_html_files($ROOT_DIRECTORY);

# close GAUGE
#print $GAUGE "\x04";
#$GAUGE->close();
eof($GAUGE);
undef($GAUGE); # this also closes the gauge... but...

# close log
print $LOGFILE ("$total_directories directories.\n\n");
$LOGFILE->close();

if ( -x $SAVELOG ) {
system("$SAVELOG $LOG > /dev/null 2>&1");
}

return 0;
} # endmain

sub init_config {
# 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="";

# some defaults:
#
# 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"}="

# tr=
";
$config_tmp{$ROOT}{"td"}=" ";
# when header is set, title, meta, stylesheet, etc...
# are discarded. So do a complete set
# such as ...<br /> # and close with "footer"<br /> $config_tmp{$ROOT}{"header"}="";<br /> $config_tmp{$ROOT}{"footer"}="";<br /> $config_tmp{$ROOT}{"menuheader_footer"}=0;<br /> $config_tmp{$ROOT}{"ext"}=$EXT;</p> <p> if ( -f "$ROOT/$CONFIG_FILE" )<br /> {<br /> open(CONFIG, "<$ROOT/$CONFIG_FILE"); # suppress warnings for now... no warnings; while ( defined($line = <CONFIG>) ) {<br /> next if /^\s*#/;<br /> chomp $line;<br /> # attempts to be forgiven about backslashes<br /> # to break lines that continues over<br /> # multiple lines<br /> if ($line =~ s/\\$//) {<br /> $line .= <CONFIG>;<br /> redo unless eof(CONFIG);<br /> }<br /> $config_tmp{$ROOT}{"$1"} = $2 if ( $line =~ m,^\s*([^=]+)=(.+),<br /> );<br /> }<br /> close(CONFIG);<br /> } else {<br /> warn << "__EOF__"; Could not find $ROOT/$CONFIG_FILE __EOF__ if ( $create_config =~ /true/ ) { if (open(CONFIG, ">$ROOT/$CONFIG_FILE")) {<br /> foreach my $key ( keys %config_tmp ) {<br /> print CONFIG "$key=" . $config_tmp{"$key"}."\n";<br /> }<br /> } else {<br /> print STDERR "Could not write $ROOT/$CONFIG_FILE. Check<br /> permissions?";<br /> }<br /> }<br /> }</p> <p> #construct a header if it doesn't yet exist:<br /> if ( $config_tmp{$ROOT}{"header"} =~ /^\s+$/ )<br /> {<br /> print $LOGFILE (": Blank header. Generating my own [$ROOT] ... \n");<br /> $config_tmp{$ROOT}{"header"}="<html><br /> <head><br /> ".$config_tmp{$ROOT}{"meta"}."</p> <p> ".$config_tmp{$ROOT}{"stylesheet"}."<br /> </head>\n".<br /> $config_tmp{$ROOT}{"body"}."<br /> \n<center>\n".<br /> $config_tmp{$ROOT}{"html_msg"}."\n";<br /> }</p> <p> #construct a footer if it doesn't yet exist:<br /> if ( $config_tmp{$ROOT}{"footer"} eq "" )<br /> {<br /> print $LOGFILE (": Blank footer. Generating my own [$ROOT] ... \n");<br /> $config_tmp{$ROOT}{"footer"}="</center>\n</body></html>";<br /> }</p> <p> # ext can be passed in a .pixdir2htmlrc file<br /> # like: ext=html or ext=php ...<br /> if (<br /> ! exists $config_tmp{$ROOT}{"ext"} ||<br /> $config_tmp{$ROOT}{"ext"} eq ""<br /> ) {<br /> # default to HTML extension<br /> $config_tmp{$ROOT}{"ext"}="html";<br /> }</p> <p> # save hash<br /> %config = %config_tmp;</p> <p> #return %config_tmp;<br /> } # end init_config</p> <p>sub mkindex {<br /> # mkindex is a private function called by<br /> # mkthumb()</p> <p> # takes a two-dimensional array in the form:<br /> # $name{base}->[0] = 'path/file'<br /> # and does a index file for e/a 'base' of<br /> # all files referenced<br /> my $hashref = $_[0]; # saves the name of the var passed<br /> # e/a key holds a full array of files<br /> my $MENU_STR = $_[1]; # a str to be included in e/a file<br /> my $i = 0;<br /> my (<br /> $this_file,<br /> $this_base<br /> ) = ""; # holds keys for hash<br /> my @files = ();</p> <p> # TODO see why this doesn't work as expected<br /> # there is no need to sort this now... more testing needed<br /> foreach $this_base ( sort keys %$hashref ) {<br /> my ($my_bgcolor,$file_name) = "";<br /> $i = 0;<br /> # read specific config file for this directory<br /> if ( -f "$this_base/$CONFIG_FILE" && ! -f<br /> "$this_base/.nopixdir2htmlrc" ) {<br /> if ( ! exists $config{$this_base} )<br /> {<br /> init_config($this_base);<br /> } else {<br /> # print only if debugging...<br /> print $LOGFILE ": Exists in DB: $this_base \n";<br /> } # end if/else not exists</p> <p> } elsif ( ! -f "$this_base/.nopixdir2htmlrc" ) {<br /> # oops, missing config... getting base file<br /> if (<br /> copy("$ROOT_DIRECTORY/$CONFIG_FILE",<br /> "$this_base/$CONFIG_FILE")<br /> ) {<br /> print $LOGFILE (": Copied ".<br /> " $ROOT_DIRECTORY/$CONFIG_FILE ".<br /> "==> $this_base/$CONFIG_FILE \n");<br /> }<br /> # now read the config file<br /> # and init a %config{this_base} hash for us<br /> init_config($this_base);<br /> }</p> <p> # "serialization"<br /> my @files = @{$$hashref{$this_base}};</p> <p> # yet another sort...<br /> # sort menus alphabetically (dictionary order):<br /> # print STDERR join(' ', @ls), "\n";<br /> my $da;<br /> my $db;<br /> @files = sort {<br /> ($da = lc $a) =~ s/[\W_]+//g;<br /> ($db = lc $b) =~ s/[\W_]+//g;<br /> $da cmp $db;<br /> } @files;</p> <p> # FILE_NAME is a global<br /> open(FILE, "><br /> ".$this_base."/".$FILE_NAME.".".$config{$this_base}{"ext"}) ||<br /> die "Couldn't write file $FILE_NAME.".$config{$this_base}{"ext"}."<br /> to $this_base";</p> <p> # start HTML<br /> print FILE ($config{$this_base}{"header"}."\n");<br /> # print menu (if any)<br /> print FILE ("$MENU_STR");<br /> # start table<br /> print FILE ($config{$this_base}{"table"}."\n");<br /> #print all picts now<br /> foreach(@files){<br /> $this_file = basename($_);<br /> if ($i == 0) {<br /> # open a new row<br /> # this row doesn't need bgcolor<br /> if ( $config{$this_base}{"tr"} =~ m/\%+bgcolor\%+/i ) {<br /> ($config{$this_base}{"tr"} = $config{$this_base}{"tr"})<br /> =~ s/\%+bgcolor\%+//i;<br /> }<br /> print FILE ($config{$this_base}{"tr"}."\n");<br /> }<br /> print FILE ("\t".$config{$this_base}{"td"}."\n");<br /> ($file_name = $this_file) =~ s/$EXT_INCL_EXPR//gi;<br /> ($file_name = $file_name) =~ s/^$THUMB_PREFIX//; # removes<br /> prefix<br /> # EXT is a global and so is THUMBNAIL<br /> print FILE ("<a href='$HTMLDIR/$file_name.".$config{$this_base}{"ext"}."'>".<br /> "<img src='$THUMBNAIL/"."$this_file'></a>\n");<br /> print FILE ("\t</td> <p>\n");<br /> if ($i<($TD-1)) { $i++; } else { # wrap and reset counter print FILE ("</tr> <p>\n");<br /> $i = 0;<br /> }<br /> } # end for e/a @files<br /> # complete missing TD<br /> if ($i != 0) {<br /> for (;$i<$TD;$i++) { print FILE ("\t".$config{$this_base}{"td"}."\n"); print FILE (" "); print FILE ("\t</td> <p>\n");<br /> }<br /> }<br /> print FILE ("</tr> <p>\n");<br /> print FILE ("</table> <p>\n");<br /> print FILE ($config{$this_base}{"footer"}."\n");<br /> print FILE ("\n");<br /> close(FILE);<br /> } # end for e/a this_base<br /> } # end mkindex</p> <p>sub mkthumb {<br /> my $ROOT = $_[0];<br /> my $MENU_STR = $_[1];<br /> # locals: reset some locals<br /> my (@ls,%pixfiles) = ();<br /> my ($thisFile,<br /> $pix_name,<br /> $file_name,<br /> $next_pix_name,<br /> $next_file_name,<br /> $last_pix_name,<br /> $last_html_file,<br /> $current_html_file,<br /> $last_file_name,<br /> $current_link,<br /> $last_link,<br /> $LAST_BASE,<br /> $NEXT_BASE,<br /> $HTMLSDIR) = "";<br /> # these two are special...<br /> # init to some strange string...<br /> my $BASE = ",\/trash";<br /> my $tmp_BASE = ",\/more_trash";</p> <p> print $LOGFILE ("= Making thumbnails in $ROOT \n");<br /> #construct array of all image files<br /> my @ary = do_file_ary("$ROOT");</p> <p> # remove duplicates:<br /> my %seen = ();<br /> my @uniq = grep(!$seen{$_}++,@ary);</p> <p> # parse array of images<br /> foreach (@uniq){<br /> $thisFile = basename($_);<br /> next if ($thisFile =~ m/$EXCEPTION_LIST/);<br /> next if ($_ =~ m/\b$THUMBNAIL\b/i);<br /> next if ($thisFile !~ m/$EXT_INCL_EXPR/i);<br /> push @ls,$_;<br /> #$TOTAL++;<br /> } #end images array creation</p> <p> # TODO make this into a function and re-use it...<br /> # sort files alphabetically (dictionary order):<br /> # maybe we should've sorted before we got here...<br /> my $da;<br /> my $db;<br /> @ls = sort {<br /> ($da = lc $a) =~ s/[\W_]+//g;<br /> ($db = lc $b) =~ s/[\W_]+//g;<br /> $da cmp $db;<br /> } @ls;</p> <p> # progressbar stuff<br /> # gauge message<br /> my $MESSAGE = "Thumbnails Creation";<br /> # initial values for gauge<br /> # TOTAL -> number of elements in ls array<br /> my ($PROGRESS,$TOTAL) = (0,( $#ls + 1 ) );<br /> progressbar_msg($MESSAGE);</p> <p> print $LOGFILE ("= $TOTAL pictures \n");<br /> foreach(@ls)<br /> {<br /> $pix_name = basename($_);<br /> # strip extension from file name<br /> ($file_name = $pix_name) =~ s/$EXT_INCL_EXPR//gi;<br /> # get base directory<br /> ( $BASE = $_ ) =~ s/(.*)\/$pix_name$/$1/g;<br /> # BASE is blank if we are already inside the directory<br /> # for which to do thumbnails, thus:<br /> if ( $BASE eq ""<br /> || ! -d $BASE )<br /> {<br /> $BASE = ".";<br /> }<br /> next if ($BASE eq $THUMBNAIL);<br /> #print STDOUT $BASE."\n";</p> <p> # this is just to clear up all<br /> # warnings from Perl..<br /> if ( $BASE gt ""<br /> && $tmp_BASE gt ""<br /> && $BASE !~ m/$tmp_BASE/ )<br /> {<br /> if (<br /> $FORCE > 0 &&<br /> ! -f "$BASE/.nopixdir2htmlrc"<br /> )<br /> {<br /> if (<br /> copy("$ROOT_DIRECTORY/$CONFIG_FILE",<br /> "$BASE/$CONFIG_FILE")<br /> )<br /> {<br /> print $LOGFILE (": Force copy ".<br /> " $ROOT_DIRECTORY/$CONFIG_FILE ".<br /> "==> $BASE/$CONFIG_FILE \n");<br /> } # end if copy<br /> } # end if FORCE</p> <p> if ( ! -f "$BASE/$CONFIG_FILE" && ! -f "$BASE/.nopixdir2htmlrc"<br /> )<br /> {<br /> if (<br /> copy("$ROOT_DIRECTORY/$CONFIG_FILE",<br /> "$BASE/$CONFIG_FILE")<br /> )<br /> {<br /> print $LOGFILE (": Copied ".<br /> " $ROOT_DIRECTORY/$CONFIG_FILE ".<br /> "==> $BASE/$CONFIG_FILE \n");<br /> } # end if copy<br /> } # end if missing $CONFIG_FILE</p> <p> # read specific config file for this directory<br /> if (! -f "$BASE/.nopixdir2htmlrc" && ! exists $config{$BASE} )<br /> {<br /> # change of base, reset two-dimensional array counter<br /> print $LOGFILE "+ Reading config for $BASE\n";<br /> # also init $config{$BASE} for us...<br /> init_config($BASE);<br /> } # end if not nopixdir2htmlrc<br /> $total_directories++;<br /> } # end if base not equal tmp_base</p> <p> # update flag<br /> $tmp_BASE = $BASE;<br /> next if ( -f "$BASE/.nopixdir2htmlrc" );</p> <p> # construct PATH for thumbnail directory<br /> $THUMBNAILSDIR="$BASE/$THUMBNAIL";</p> <p> #print STDOUT $HTMLSDIR."\n";<br /> if (!-d "$THUMBNAILSDIR") {<br /> print $LOGFILE ("= Making thumbnail directory in $BASE\n");<br /> mkdir("$THUMBNAILSDIR",0755);<br /> }</p> <p> if ( !-f "$THUMBNAILSDIR/".$THUMB_PREFIX.$pix_name ){<br /> print $LOGFILE ("\n= Converting file $BASE/$pix_name into<br /> $THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name \n");<br /> my $image = Image::Magick->new;<br /> $image->Read("$BASE/$pix_name");<br /> $image->Resize("$PERCENT");<br /> $image->Write("$THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name");<br /> undef $image;<br /> # TODO if we could not load Image::Magick, see if "convert" is<br /> installed and use<br /> # this instead:<br /> #system("convert -geometry $PERCENT $BASE/$pix_name<br /> $THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name");<br /> #if ( $? != 0 ) {<br /> # die "ERROR: conversion failed\n $! ";<br /> #}<br /> print $LOGFILE ("\n");<br /> }<br /> # end if thumbnail file</p> <p> # save pixname for the index.html file<br /> push @{$pixfiles{$BASE}},<br /> "$THUMBNAILSDIR/$THUMB_PREFIX"."$pix_name";<br /> # update flags<br /> $LAST_BASE = $BASE;<br /> # update progressbar<br /> progressbar($PROGRESS,$TOTAL);<br /> $PROGRESS++;<br /> } #end foreach @ls</p> <p> if ( $NOINDEX == 0 ) {<br /> mkindex(\%pixfiles,$MENU_STR); # pass hash reference<br /> # and a menu string<br /> # to be included in e/a file<br /> }</p> <p>} # end mkthumb</p> <p>sub thumb_html_files {<br /> # creates an HTML page for a thumbnail<br /> my $ROOT = $_[0];<br /> # locals<br /> my @ls = ();<br /> my $i = 0;<br /> my ($thisFile,<br /> $pix_name,<br /> $file_name,<br /> $next_pix_name,<br /> $next_file_name,<br /> $last_pix_name,<br /> $current_html_file,<br /> $last_file_name,<br /> $current_link,<br /> $last_link,<br /> $LAST_BASE,<br /> $NEXT_BASE,<br /> $HTMLSDIR) = "";<br /> # TODO find a more elegant solution here<br /> # init to dummy string:<br /> my $BASE = "trash/\file";<br /> my $tmp_BASE = "garbage\/file";<br /> my $last_html_file = "this_is/dummy\string";</p> <p> my @ary = ();</p> <p> if (<br /> defined $pixfile[0]<br /> && -f $pixfile[0]<br /> )<br /> {<br /> # copy that array instead:<br /> @ary = @pixfile;<br /> } else {<br /> # construct array of all files<br /> @ary = do_file_ary("$ROOT");<br /> }</p> <p> # remove duplicates:<br /> my %seen = ();<br /> my @uniq = grep(!$seen{$_}++,@ary);</p> <p> # parse array of files, get images only<br /> # from it:<br /> foreach (@uniq){<br /> $thisFile = basename($_);<br /> next if ($thisFile =~ m/$EXCEPTION_LIST/);<br /> next if ($_ =~ m/\/$THUMBNAIL\/.*$EXT_INCL_EXPR$/i);<br /> next if ($thisFile !~ m/$EXT_INCL_EXPR/i);<br /> push @ls,$_;<br /> } #end images array creation</p> <p> # yet yet another sort!!! goodness<br /> # TODO make this into a function and re-use it...<br /> # sort files alphabetically (dictionary order):<br /> # maybe we should've sorted before we got here...<br /> my $da;<br /> my $db;<br /> @ls = sort {<br /> ($da = lc $a) =~ s/[\W_]+//g;<br /> ($db = lc $b) =~ s/[\W_]+//g;<br /> $da cmp $db;<br /> } @ls;</p> <p> # progressbar stuff<br /> # gauge message<br /> my $MESSAGE = "HTML Creation";<br /> # initial values for gauge, note total<br /> # is number of elements in array ;-)<br /> my ($PROGRESS,$TOTAL) = (0,$#ls);<br /> progressbar_msg($MESSAGE);<br /> #print all picts now<br /> # $#VAR gets number of elements of an array variable<br /> 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") ||<br /> die "Couldn't write file $current_html_file";</p> <p> # start HTML<br /> print FILE ($config{$BASE}{"header"}."\n");<br /> # start table<br /> print FILE ($config{$BASE}{"table"}."\n");<br /> print FILE ("<br /> <tr> <td>\n");<br /> # image here<br /> print FILE ("<img src='../$pix_name'>\n");<br /> print FILE ("</td> </tr> <p>\n<br /> <tr> <td valign='bottom' align='center'> <div align='center'>\n");<br /> # backward link here<br /> if ( $last_html_file ne "this_is/dummy\string"<br /> && -f $last_html_file<br /> && ($BASE eq $LAST_BASE) )<br /> {<br /> print FILE ("<a href='$last_link'><==</a>\n");<br /> } else {<br /> print FILE ("<==");<br /> }<br /> # home link here<br /> print FILE (" | <a href='../$FILE_NAME.".$config{$BASE}{"ext"}."'>HOME</a> | \n");</p> <p> if ( -f $ls[$i+1] ) {<br /> $next_pix_name = "....";<br /> # calculate next base<br /> $next_pix_name = basename($ls[$i+1]);<br /> # get next base directory<br /> ( $NEXT_BASE = $ls[$i+1] ) =~ s/(.*)\/$next_pix_name$/$1/g;<br /> }<br /> # forward link here<br /> if ( -f $ls[$i+1] && ($BASE eq $NEXT_BASE) ) {<br /> $next_file_name = "";<br /> ($next_file_name = $next_pix_name) =~ s/$EXT_INCL_EXPR//gi;<br /> #print FILE ("==>");<br /> print FILE ("<a href='$next_file_name.".$config{$BASE}{"ext"}."'>==></a>\n");<br /> } else {<br /> print FILE ("==>");<br /> # TODO would be nice to jump to next directory in the<br /> # array...<br /> #print FILE (" <a href='../$next_file_name.$EXT'> |=>></a><br /> \n");<br /> }</p> <p> print FILE ("</p></div> </td> </tr> <p>\n");<br /> print FILE ("</table> <p>\n");<br /> print FILE ($config{$BASE}{"footer"}."\n");<br /> close(FILE);<br /> # end HTML<br /> print $LOGFILE ("\n");<br /> # keep track of links<br /> $last_html_file = $current_html_file;<br /> $last_link = $current_link;<br /> # update flags<br /> $LAST_BASE = $BASE;<br /> $NEXT_BASE = "";<br /> #$PRINT_NEXT_LINK = 0;</p> <p> # update progressbar<br /> progressbar($PROGRESS,$TOTAL);<br /> $PROGRESS++;<br /> } #end foreach<br /> } # end thumb_html_files</p> <p>sub menu_file {<br /> #---------------------------------------------#<br /> # It creates a menu.$EXT file at<br /> # the root level of the picture<br /> # directory (at the first<br /> # directory that was passed to the script) or<br /> # it puts a menu in e/a index.$EXT file<br /> #<br /> # if there is a file named .new<br /> # inside the given directory,<br /> # then a IMG tag will be put in<br /> # front of the link with an image<br /> # src=myscript{new} in it<br /> #<br /> # Thus in the config file put a line as such:<br /> # new=http://images.server.com/new_icon.png;<br /> #----------------------------------------------#</p> <p> init_config($ROOT_DIRECTORY);</p> <p> my $MENU_STR = ""; # return this instead of making file<br /> my $IMG = "";<br /> my $line = "";<br /> #my $thisFile= "";<br /> my $x=0; # counts number of links<br /> my $y=0; # counts number of td's<br /> my $i=0; # general purpose counter<br /> my $j=0; # count number of TR's<br /> my @ls = ();<br /> my $ts = "";<br /> my @files=();<br /> my @pixdir = (); # reset array</p> <p> my @ary = do_dir_ary("$ROOT_DIRECTORY");</p> <p> # remove duplicates:<br /> my %seen = ();<br /> my @uniq = grep(!$seen{$_}++,@ary);</p> <p> # for e/a directory here<br /> # check if a .nopixdir2htmlrc file exists<br /> # if it does, then skip it and do the next one.<br /> # if it doesn't, then assume this will contain<br /> # a index.$EXT file and add it to the menu.<br /> #<br /> # TODO<br /> # If we check whether the index.$EXT file exists<br /> # first, then we get files with no menu table...<br /> # We should find a way to correct this.<br /> # Take into consideration that this function is called<br /> # before we even attempt to build the index.$EXT files<br /> # thus, that makes things kind of difficult a bit.<br /> # So, we should check if at least one .jpg|.gif|.png<br /> # file exists in the current $directory. That should<br /> # be done by do_dir_ary above<br /> #<br /> foreach my $directory (@uniq){<br /> next if (-f "$directory/.nopixdir2htmlrc");</p> <p> if (<br /> !-f "$directory/.nopixdir2htmlrc"<br /> ) {<br /> # note that @ls holds the HTML links...<br /> # thus, paths are relative and not absolute here:</p> <p> $ls[$x] =<br /> "$directory/$FILE_NAME.".$config{$ROOT_DIRECTORY}{"ext"}; # why not push()?<br /> just to keep count I guess...<br /> $x++;<br /> }<br /> }<br /> $total_links = $x;</p> <p> # sort menus alphabetically (dictionary order):<br /> # print STDERR join(' ', @ls), "\n";<br /> my $da;<br /> my $db;<br /> @ls = sort {<br /> ($da = lc $a) =~ s/[\W_]+//g;<br /> ($db = lc $b) =~ s/[\W_]+//g;<br /> $da cmp $db;<br /> } @ls;</p> <p> if ( $MENUONLY > 0 ) {<br /> open(FILE, "><br /> ".$ROOT_DIRECTORY."/".$MENU_NAME.".".$config{$ROOT_DIRECTORY}{"ext"}) ||<br /> die "Couldn't write file<br /> $MENU_NAME.".$config{$ROOT_DIRECTORY}{"ext"}." to $ROOT_DIRECTORY";<br /> }</p> <p> # menus are now part of the index.EXT...<br /> # print header only if menuonly is set and we want to show<br /> # the header/footer set in .pixdir2htmlrc<br /> if ( $MENUONLY > 0 && $config{$ROOT_DIRECTORY}{"menuheader_footer"} > 0<br /> ) {<br /> print FILE ($config{$ROOT_DIRECTORY}{"header"}."\n");<br /> }</p> <p> # generate menu<br /> #<br /> # When using nautilus we are off by one:<br /> # TODO needs more testing<br /> # if ( $nautilus_root gt "" )<br /> # {<br /> # $total_links-- ;<br /> # }</p> <p> if ( $total_links > 1 )<br /> {<br /> if ( $MENUONLY > 0 )<br /> {<br /> print FILE ($config{$ROOT_DIRECTORY}{"table"}."\n");<br /> }<br /> $MENU_STR .= $config{$ROOT_DIRECTORY}{"table"}."\n";<br /> # print all links now<br /> my $tmp_tr = ""; # used to color the rows<br /> while($x>0){<br /> # temporarily turn off warnings<br /> no warnings;<br /> # TODO<br /> # menu only routine: prints to a file... should merge<br /> # with the str portion (see else)<br /> #<br /> if ( $MENUONLY > 0 ) {<br /> if ($config{$ROOT_DIRECTORY}{"tr"}=~m/\%+bgcolor\%+/i){<br /> if (($j % 2) == 0){<br /> ($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~<br /> s/\%+bgcolor\%+/bgcolor=#efefef/i;<br /> } else {<br /> ($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~<br /> s/\%+bgcolor\%+//i;<br /> }</p> <p> print FILE ($tmp_tr."\n");</p> <p> } else {<br /> print FILE ($config{$ROOT_DIRECTORY}{"tr"}."\n");<br /> }<br /> for ($y=1;$y<=$menu_td;$y++){ # close the TD tags if ($y > 1) {<br /> print FILE ("\t </td> <p> \n");<br /> }<br /> print FILE ("\t".$config{$ROOT_DIRECTORY}{"td"}."\n");</p> <p> if ( $ls[$i] ne "" ) {<br /> # if link exists, otherwise leave it blank<br /> # TODO there is a better way to do this... find<br /> it...<br /> ($ts = $ls[$i]) =~<br /> s#(.*)/$FILE_NAME.$config{$ROOT_DIRECTORY}{"ext"}#$1#gi;<br /> # from nautilus one cannot pass arguments<br /> # "--menuonly" but... just to keep things<br /> # consistent...<br /> # if number of characters is greater than $STR_LIMIT<br /> # truncate $ts to a few characters.<br /> if ( $nautilus_root gt "" ) {<br /> ( $ls[$i] = $ls[$i] ) =~ s,$nautilus_root/,,g;<br /> ( $ts = $ts ) =~ s,$nautilus_root/*,,g;<br /> }</p> <p> # remove CUT_DIRS number of directories from ts<br /> if ( $CUT_DIRS > 0 )<br /> {<br /> $ts = cut_dirs($ts,$CUT_DIRS);<br /> }</p> <p> my $tmp_ts = str_truncate($ts);</p> <p> $IMG = (-f "$ts/.new") ? "<img valign='middle' border=0 src='".$config{$ROOT_DIRECTORY}{"new"}."' alt='new'>":""; # if .new<br /> file<br /> $ts = ucfirst($tmp_ts);<br /> print FILE ("<a href='".$config{$ROOT_DIRECTORY}{"uri"}."/$ls[$i]' target='_top'>$IMG<br /> $ts</a>\n");<br /> } else {<br /> print FILE (" ");<br /> }<br /> $i++;<br /> $x--;<br /> } # end for $y<br /> print FILE ("</tr> <p>\n");<br /> $j++; # incr TR counter<br /> } else {<br /> # general menu routine<br /> # TODO cleanup<br /> if ($config{$ROOT_DIRECTORY}{"tr"}=~m/\%+bgcolor\%+/i){<br /> if (($j % 2) == 0){<br /> ($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~<br /> s/\%+bgcolor\%+/bgcolor=#efefef/i;<br /> } else {<br /> ($tmp_tr = $config{$ROOT_DIRECTORY}{"tr"}) =~<br /> s/\%+bgcolor\%+//i;<br /> }<br /> $MENU_STR .= $tmp_tr."\n";<br /> } else {<br /> $MENU_STR .= $config{$ROOT_DIRECTORY}{"tr"}."\n";<br /> }<br /> for ($y=1;$y<=$menu_td;$y++){ # close the TD tags if ($y > 1) {<br /> $MENU_STR .= "\t </td> <p> \n";<br /> }<br /> $MENU_STR .= "\t".$config{$ROOT_DIRECTORY}{"td"}."\n";<br /> # menu entries<br /> if ( $ls[$i] ne "" ) {<br /> # if link exists, otherwise leave it blank<br /> # TODO there is a better way to do this... find<br /> it...<br /> ( $ts = $ls[$i]) =~<br /> s,(.*)/$FILE_NAME.$config{$ROOT_DIRECTORY}{"ext"},$1,gi;<br /> $IMG = (-f "$ts/.new") ? "<img valign='middle' border=0 src='".$config{$ROOT_DIRECTORY}{"new"}."' alt='new'>":""; # if .new<br /> file<br /> # if number of characters is greater than $STR_LIMIT<br /> # truncate $ts to a few characters.<br /> if ( $nautilus_root gt "" ) {<br /> ( $ls[$i] = $ls[$i] ) =~ s,$nautilus_root/,,g;<br /> ( $ts = $ts ) =~ s,$nautilus_root/*,,g;<br /> }</p> <p> # remove CUT_DIRS number of directories from ts<br /> if ( $CUT_DIRS > 0 )<br /> {<br /> $ts = cut_dirs($ts,$CUT_DIRS);<br /> }</p> <p> my $tmp_ts = str_truncate($ts);<br /> $ts = ucfirst($tmp_ts);<br /> # $ls tends to hold the whole filename path+filename<br /> # we don't care about the whole path here...<br /> $MENU_STR .= "<a href='".$config{$ROOT_DIRECTORY}{"uri"}."/$ls[$i]' target='_top'>$IMG<br /> $ts</a>\n";<br /> } else {<br /> $MENU_STR .= " ";<br /> }<br /> $i++;<br /> $x--;<br /> } # end for $y<br /> $MENU_STR .= "</tr> <p>\n";<br /> $j++; # incr TR counter<br /> } # end if/else menuonly<br /> }<br /> if ( $MENUONLY > 0 ) {<br /> print FILE ("</table> <p>\n");<br /> }<br /> $MENU_STR .= "</table> <p>\n";<br /> } # end if total_links<br /> else<br /> {<br /> print $LOGFILE (": Not a single link found\n");<br /> }<br /> # see previous notes on header<br /> if ( $MENUONLY > 0 && $config{$ROOT_DIRECTORY}{"menuheader_footer"} > 0)<br /> {<br /> print FILE ($config{$ROOT_DIRECTORY}{"footer"}."\n");<br /> }<br /> if ( $MENUONLY > 0 ) {<br /> close(FILE);<br /> }<br /> if ( $total_links > 1 ) {<br /> print $LOGFILE (": $total_links links in menu.\n");<br /> }<br /> return $MENU_STR;<br /> } #end menu_file</p> <p># ---- HELPER functions ----- #</p> <p>sub str_truncate<br /> {<br /> my $str = shift;<br /> my $str_length = length ($str);<br /> $str = ($str_length > $STR_LIMIT) ?<br /> "...".substr($str,($STR_LIMIT/2),$str_length):$str;<br /> # return truncated string<br /> return $str;<br /> } #end str_truncate</p> <p>sub progressbar<br /> {<br /> my ($PROGRESS,$TOTAL)=@_;<br /> chomp($PROGRESS);<br /> chomp($TOTAL);<br /> my $current = 0;<br /> # make sure we don't divide by 0<br /> if ( $TOTAL > 0 )<br /> {<br /> $current = sprintf( "%02d",($PROGRESS/$TOTAL) * 100 );<br /> print $GAUGE $current."\n";<br /> }<br /> } # end progressbar</p> <p>sub progressbar_msg<br /> {<br /> my ($MESSAGE) = @_;</p> <p> chomp($MESSAGE);<br /> print $GAUGE "XXX\n".$MESSAGE."\nXXX\n";<br /> } # end progressbar_msg</p> <p>sub do_dir_ary {<br /> # uses find() to recur thru directories<br /> # returns an array of directories<br /> # i.e. in directory "a" with structure:<br /> # /a<br /> # /a/b<br /> # /a/b/c<br /> # /a/b2/c2<br /> #<br /> # my @ary = &do_dir_ary(".");<br /> #<br /> # will yield:<br /> # a<br /> # a/b<br /> # a/b/c<br /> # a/b2/c2<br /> #</p> <p> my $ROOT = shift;<br /> my %opt = (wanted => \&process_dir, no_chdir=>1);<br /> find(\%opt,$ROOT);<br /> return @pixdir;<br /> } # end do_dir_ary</p> <p>sub process_dir {<br /> my $base_name = basename($_);<br /> if (<br /> !-f $_<br /> && $base_name !~ m/^($EXCEPTION_LIST)$/<br /> && $base_name !~ m/\b$THUMBNAIL\b/<br /> && $base_name !~ m/\b$HTMLDIR\b/<br /> && $base_name !~ m/^\.[a-zA-Z0-9]+$/<br /> )<br /> {<br /> s/^\.\/*//g;<br /> push @pixdir,$_;<br /> #print $_ . "\n";<br /> }<br /> } # end process_dir</p> <p>sub do_file_ary {<br /> # uses find() to recur thru directories<br /> # returns an array of files<br /> # i.e. in directory "a" with the files:<br /> # /a/file.txt<br /> # /a/b/file-b.txt<br /> # /a/b/c/file-c.txt<br /> # /a/b2/c2/file-c2.txt<br /> #<br /> # my @ary = &do_file_ary(".");<br /> #<br /> # will yield:<br /> # a/file.txt<br /> # a/b/file-b.txt<br /> # a/b/c/file-c.txt<br /> # a/b2/c2/file-c2.txt<br /> #<br /> my $ROOT = shift;<br /> my %opt = (wanted => \&process_file, no_chdir=>1);<br /> find(\%opt,$ROOT);<br /> return @pixfile;<br /> } # end do_file_ary</p> <p>sub process_file {<br /> my $base_name = basename($_);<br /> if (<br /> -f $_<br /> && $base_name !~ m/^($EXCEPTION_LIST)$/<br /> && $base_name !~ m/\b$THUMBNAIL\b/<br /> && $base_name !~ m/\b$HTMLDIR\b/<br /> && $base_name !~ m/^\.[a-zA-Z0-9]+$/<br /> )<br /> {<br /> s/^\.\/*//g;<br /> push @pixfile,$_;<br /> }<br /> } #end process_file</p> <p>sub cut_dirs {<br /> # call like cut_dirs($ts,$CUT_DIRS);<br /> # where ts is a path in the form "path/to/something"<br /> # and $CUT_DIRS is an integer<br /> my $path = shift;<br /> my $cut = shift;<br /> # TODO is there a way to know the OS separator string in Perl<br /> # a la Python?<br /> $path =~ s,^/,,g; # remove leading slashes<br /> my @tmp_path = split(/\//,$path);<br /> my $tmp_str = "";</p> <p> for ( my $i = 0; $i <= $#tmp_path; $i++ ) { if ( $i >= $cut ) # to be safe, display the last name<br /> {<br /> $tmp_str .= $tmp_path[$i]."/";<br /> }<br /> }<br /> return $tmp_str;<br /> } # end cut_dirs<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/pprint ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/pprint<br /> <code><br /> #!/bin/sh<br /> # Copyright (C) Sept 13, 2001 Shane Mueller <smueller@umich.edu><br /> # http://g-scripts.sourceforge.net<br /> #<br /> # pprint: This script designed for use with the Nautilus File Manager<br /> # This script requires the unix utility enscript, and may require<br /> # modification based upon your local printing command.<br /> # It will either print directly to the default printer or<br /> # will generate a pretty file from the selected text files, and either<br /> # print to printer or generate files from selected files.<br /> #<br /> # This does file-type sensitive selection.</p> <p># This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU Library General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> <p>#First, process each of the selected file</p> <p>for arg<br /> do<br /> filetype=$(file "$arg")</p> <p> #Do file-type sensitive processing<br /> case "$filetype" in<br /> *text*) #Any type of Text file<br /> #This allows you to select how the file is processed<br /> 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`</p> <p> case $choice in<br /> 1) ##print using enscript<br /> enscript -2 -G2rE -U1 --borders --word-wrap "$arg"<br /> ;;</p> <p> 2) ##print to a .ps file of your choice<br /> NEWNAME=`gdialog --title "Generate Postscript File" --inputbox "Enter Filename (include extension)" 200 100 "$arg".ps 2>&1`<br /> enscript -2 -G2rE -U1 --borders --word-wrap -p "$NEWNAME" "$arg"<br /> ;;</p> <p> 3) ##Generate an .html<br /> NEWNAME=`gdialog --title "Generate .html" --inputbox "Enter Filename (include extension)" 200 100 "$arg".html 2>&1`<br /> enscript -E --color -W html -p "$NEWNAME" "$arg"<br /> ;;</p> <p> 4) ##Generate an .rtf<br /> NEWNAME=`gdialog --title "Generate .rtf" --inputbox "Enter Filename (include extension)" 200 100 "$arg".rtf 2>&1`<br /> enscript -E -W rtf -p "$NEWNAME" "$arg"<br /> ;;</p> <p> *) ##Don't do nothing-cancel key<br /> ;;<br /> esac</p> <p> ;;<br /> *postscript*) ##send to printer directly<br /> lpr "$arg"<br /> ;;</p> <p> ##Other file types can go here if you know how to process them.</p> <p> *)<br /> gdialog --msgbox "Uncertain how to process file $arg: \n File type $filetype" 200 200</p> <p> esac</p> <p>done</code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/print ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/print<br /> <code><br /> #!/bin/bash</p> <p># FILE: print --<br /> # AUTHOR: W. Michael Petullo <mike@flyn.org><br /> # DATE: 31 May 2001<br /> #<br /> # Copyright (C) 2001 W. Michael Petullo <mike@flyn.org><br /> # All rights reserved.<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA</p> <p>lpr $*<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/print_with_openoffice ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/print_with_openoffice<br /> <code><br /> #!/bin/sh<br /> #<br /> # This script prints the selected files with openoffice.org<br /> # especially useful for openoffice files ;-)<br /> #<br /> # the "quoted..." line handles multiple files with spaces<br /> # (like shown on the g-scripts site)<br /> #<br /> quoted=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | awk 'BEGIN {FS = "\n" } { printf "\"%s\" ", $1 }' | sed -e s#\"\"##)<br /> eval "ooffice -p $quoted"<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/ps2pdf ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/ps2pdf<br /> <code><br /> #!/bin/sh<br /> cd $NAUTILUS_SCRIPT_CURRENT_URI<br /> ps2pdf $@</code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/scp2host ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/scp2host<br /> <code><br /> #!/bin/sh<br /> #scp to host<br /> Eterm --trans --shade 40 --scrollbar off --menubar off -e scp $@ user@host:~</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/scp_to_host ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/scp_to_host<br /> <code><br /> #!/bin/sh<br /> #<br /> # This script scp's file/s to a given url.<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Copyright (C) Keith Conger <acid@twcny.rr.com><br /> #<br /> # Install in your ~/Nautilus/scripts directory.<br /> # You need to be running Nautilus 1.0.3 +</p> <p>URL=$(gdialog --title "scp file(s) to?" --inputbox "url for host(ie.user@myhost.com:/tmp)" 200 550 2>&1)</p> <p>gnome-terminal -t "Copying file.." -x scp $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $URL</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/search_n_replace ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/search_n_replace<br /> <code><br /> #!/bin/bash</p> <p># FILE: search_n_replace --<br /> # AUTHOR: W. Michael Petullo <mike@flyn.org><br /> # DATE: 31 May 2001<br /> #<br /> # Copyright (C) 2001 W. Michael Petullo <mike@flyn.org><br /> # All rights reserved.<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA</p> <p>SEARCH=`gdialog --title "Search For" --inputbox "Regular Expression" 200 450 2>&1`<br /> REPLACE=`gdialog --title "Replace With" --inputbox "String" 200 450 2>&1`<br /> TMP=`mktemp /tmp/search_n_replace.XXXXXX`</p> <p>trap 'rm -f $TMP' EXIT SIGHUP SIGINT SIGTERM</p> <p>for file in $*; do<br /> sed -e "s/$SEARCH/$REPLACE/g" $file > $TMP<br /> cp $file $file.bak<br /> mv $TMP $file<br /> done</code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/secure_copy ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/secure_copy<br /> <code><br /> #!/bin/bash</p> <p>###############################################################################<br /> # secure copy (scp) Files to a given location<br /> ###############################################################################<br /> #<br /> # AUTHOR:       Brian Connelly <pub@bconnelly.net> #<br /> # DESCRIPTION:  This script does what its name implies-- it copies the files<br /> #               which have been selected in Nautilus to a remote or local<br /> #               location using the scp command.<br /> #<br /> # REQUIREMENTS: Nautilus file manager<br /> #               scp (see OpenSSH)<br /> #               gdialog, which is usually included in the gnome-utils package<br /> #<br /> # INSTALLATION: GNOME 1.4.x: copy this script to the ~/Nautilus/scripts<br /> #                       directory<br /> #               GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory<br /> #<br /> # USAGE:        Select the files that you would like to copy in Nautilus,<br /> #               right click, go to Scripts, and then select this script.<br /> #               You will then be asked to select a target destination.<br /> #               This can be one of the following:<br /> #<br /> #               Ex. 1. /tmp - copy the selected files to /tmp ON THIS MACHINE<br /> #               Ex. 2. something.com:/home/somegyy - copy the selected files<br /> #                       to /home/someguy directory on the machine something.com.<br /> #                       NOTE: Your username on that machine must either be the<br /> #                             same as your username on the local machine as on<br /> #                             something.com, or the proper username must be<br /> #                             specified in the .ssh_hosts file<br /> #               Ex. 3. someguy@something.com:/home/someguy - copy the selected<br /> #                       files to /home/someguy on something.com.  Your username<br /> #                       on something.com is someguy.<br /> #<br /> # VERSION INFO:<br /> #               0.1 (20020923) - Initial public release<br /> #<br /> # COPYRIGHT:    Copyright (C) 2002 Brian Connelly <connelly@purdue.edu><br /> #<br /> # LICENSE:      GNU GPL<br /> #<br /> ###############################################################################</p> <p>SCRIPT_TITLE=$(basename "$0")<br /> SCP_BIN=$(which scp) || (gdialog --title "$SCRIPT_TITLE Error" --msgbox "scp<br /> cannot be found.  It is either not in your PATH or not installed on this<br /> system" 400 400 2>&1 && exit)<br /> TARGET=""</p> <p>if [ -z $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS ]; then<br /> gdialog --title "$SCRIPT_TITLE Error" --msgbox "No files have been selected"<br /> 400 400 2>&1<br /> exit<br /> fi</p> <p>while [ -z $TARGET ]<br /> do<br /> TARGET=$(gdialog --title "$SCRIPT_TITLE" --inputbox "Enter Target<br /> Destination:" 400 400 "" 2>&1) || exit</p> <p>if [ -z $TARGET]; then<br /> gdialog --title "$SCRIPT_TITLE Error" --msgbox "You must choose a target<br /> destination" 400 400 2>&1<br /> fi<br /> done</p> <p>($SCP_BIN -r $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $TARGET >&<br /> /tmp/scripterror && rm /tmp/scripterror) || (gdialog --title "$SCRIPT_TITLE<br /> Error" --msgbox "Could not execute scp: `cat /tmp/scripterror`" 400 400 2>&1<br /> && rm /tmp/scripterror)<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileProcessing/superexec.py ====</h3> <p>$ cat nautilus-scripts/Varios/FileProcessing/superexec.py<br /> <code><br /> #!/usr/bin/env python</p> <p>"""</p> <p>superexec -- Nautilus script for building command pipelines</p> <p>Version: 0.1<br /> Requitements: python, pygtk2</p> <p>Copyright (C) 2002 Krzysztof Luks <kluks@iq.pl><br /> Distributed under the terms of GNU GPL version 2 or later</p> <p>This script allows building complicated command pipelines without need<br /> to use shell. Commands will be executed in following order:</p> <p>command1 <selected file(s)> [| command2 | ... | commandN]</p> <p>Output can be saved to file, printed on screen or sent to last command<br /> in pipeline.</p> <p>Some tips:<br /> - superexec can also be used to run single command (e.g. fortune)<br /> - if you want to send selected file to stdin of the first command<br /> 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:<br /> button.connect('clicked', del_row_cb, hbox)<br /> else:<br /> button.set_sensitive(gtk.FALSE)<br /> hbox.pack_start(button)</p> <p> entrybox.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)<br /> hbox.show_all()</p> <p>def del_row_cb(widget, data = None):<br /> entry = data.get_children()[0]<br /> entries.remove(entry)<br /> entrybox.remove(data)</p> <p>def execute_cb(widget, data = None):<br /> str = entries[0].get_text() + ' '</p> <p> paths = parse_nautilus_environment()['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS']<br /> for path in paths:<br /> str += string.strip(path) + ' '</p> <p> if len(entries) == 2:<br /> str += ' | ' + entries[-1].get_text()<br /> elif len(entries) > 2:<br /> str += ' | '<br /> for e in range(1, len(entries)-1):<br /> str += entries[e].get_text() + ' | '<br /> str += entries[-1].get_text()</p> <p> import tempfile<br /> tmp_out = None<br /> tmp_err = tempfile.mktemp('superexec')</p> <p> str += ' 2> ' + tmp_err</p> <p> if lr[-1] == 'file':<br /> str += ' > ' + file_entry.get_text()<br /> elif lr[-1] == 'show':<br /> tmp_out = tempfile.mktemp('superexec')<br /> str += ' > ' + tmp_out</p> <p> decision = show_dialog(gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, str)</p> <p> print 'I would execeute: ',<br /> print str</p> <p> if decision == gtk.RESPONSE_OK:<br /> res = os.system(str)<br /> if res < 0: show_dialog(gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, 'Fork failed') elif res > 0:<br /> f = open(tmp_err)<br /> msg = ''<br /> for line in f.readlines():<br /> msg += line<br /> f.close()<br /> show_dialog(gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, msg)<br /> elif lr[-1] == 'show':<br /> show_output(tmp_out)<br /> os.remove(tmp_err)<br /> os.remove(tmp_out)</p> <p>def button_cb(widget, data = None):<br /> print data</p> <p>def radio_cb(widget, data = None):<br /> if data == 'file' and widget.get_active():<br /> file_entry.set_sensitive(1)<br /> file_button.set_sensitive(1)<br /> else:<br /> file_entry.set_sensitive(0)<br /> file_button.set_sensitive(0)</p> <p> lr.pop()<br /> lr.append(data)</p> <p>def make_buttons():<br /> box = gtk.VBox(gtk.FALSE, 0)</p> <p> hbox = gtk.HBox(gtk.FALSE, 0)<br /> widget = gtk.RadioButton(None, 'show')<br /> widget.connect('toggled', radio_cb, 'show')<br /> widget.set_active(1)<br /> group = widget<br /> hbox.pack_start(widget)<br /> widget = gtk.RadioButton(group, 'last command')<br /> widget.connect('toggled', radio_cb, 'last')<br /> hbox.pack_start(widget)<br /> widget = gtk.RadioButton(group, 'file')<br /> widget.connect('toggled', radio_cb, 'file')<br /> hbox.pack_start(widget)<br /> box.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)</p> <p> hbox = gtk.HBox(gtk.FALSE, 0)<br /> widget = gtk.Entry(max = 0)<br /> f_entry = widget<br /> f_entry.set_sensitive(0)<br /> hbox.pack_start(widget)<br /> widget = gtk.Button(label = 'Browse...')<br /> f_button = widget<br /> f_button.set_sensitive(0)<br /> widget.connect('clicked', execute_cb)<br /> hbox.pack_start(widget)<br /> box.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)</p> <p> hbox = gtk.HBox(gtk.FALSE, 0)<br /> widget = gtk.Button(stock = gtk.STOCK_EXECUTE)<br /> widget.connect('clicked', execute_cb)<br /> hbox.pack_start(widget)<br /> widget = gtk.Button(stock = gtk.STOCK_CLOSE)<br /> widget.connect('clicked', destroy_cb)<br /> hbox.pack_start(widget)<br /> box.pack_start(hbox, gtk.FALSE, gtk.FALSE, 2)</p> <p> return box, f_entry, f_button</p> <p>def show_dialog(type, buttons, str):<br /> dialog = gtk.MessageDialog(win,<br /> gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,<br /> type, buttons, str)<br /> result = dialog.run()<br /> dialog.destroy()<br /> return result</p> <p>def show_output(file):<br /> dialog = gtk.Dialog("Command output", win, 0,<br /> (gtk.STOCK_SAVE_AS, gtk.RESPONSE_OK,<br /> gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL))<br /> buff = gtk.TextBuffer(None)<br /> f = open(file)<br /> for line in f.readlines():<br /> buff.insert_at_cursor(line, len(line))<br /> f.close()<br /> tv = gtk.TextView()<br /> tv.set_buffer(buff)<br /> tv.set_editable(gtk.FALSE)<br /> tv.set_cursor_visible(gtk.FALSE)</p> <p> sw = gtk.ScrolledWindow()<br /> sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)<br /> sw.set_shadow_type(gtk.SHADOW_IN)<br /> sw.add(tv)</p> <p> dialog.vbox.pack_start(sw, gtk.TRUE, gtk.TRUE, 0)<br /> dialog.set_default_size(640, 480)<br /> dialog.show_all()<br /> result = dialog.run()<br /> dialog.destroy()<br /> return result</p> <p>entries = []<br /> lr = ['show']</p> <p>win = gtk.Window()<br /> win.set_title('superexec')<br /> win.connect("delete_event", destroy_cb)<br /> win.set_border_width(5)</p> <p>buttonbox, file_entry, file_button = make_buttons()<br /> entrybox = gtk.VBox(gtk.FALSE, 0)<br /> entrybox.set_border_width(5)</p> <p>frame1 = gtk.Frame('Command chain')<br /> frame1.add(entrybox)<br /> frame2 = gtk.Frame('Output')<br /> frame2.add(buttonbox)</p> <p>mainbox = gtk.VBox(gtk.FALSE, 0)<br /> mainbox.pack_start(frame1)<br /> mainbox.pack_start(frame2)</p> <p>win.add(mainbox)<br /> add_row_cb(None)</p> <p>geom = parse_nautilus_environment()['NAUTILUS_SCRIPT_WINDOW_GEOMETRY']<br /> if len(geom) > 0:<br /> geom = geom[0]<br /> geom = geom.replace('x', '+').split('+')<br /> # position script window in the center of current nautilus window<br /> x = (int(geom[0]) / 2) + int(geom[2])<br /> y = (int(geom[1]) / 2) + int(geom[3])<br /> win.move(x, y)</p> <p>win.show_all()<br /> gtk.main()<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/burn_dir ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/burn_dir<br /> <code><br /> #!/bin/bash</p> <p># FILE: burn_dir --<br /> # AUTHOR: W. Michael Petullo <mike@flyn.org><br /> # DATE: 31 May 2001<br /> #<br /> # Copyright (C) 2001 W. Michael Petullo <mike@flyn.org><br /> # All rights reserved.<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA</p> <p>bbbdir -v "$1" -i "$1" | bbb -s 4 -x<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/burn_iso ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/burn_iso<br /> <code><br /> #!/bin/sh<br /> # Placed into the Public Domain 2/2002 by Shane T. Mueller<br /> # This will use cdrecord to burn an .iso file to your ard-coded<br /> # cd-rom writer<br /> # You should do a cdrecord -scanbus to determine the dev setting<br /> # for your cd-rom writing device. For me, it looked like this:<br /> # $ cdrecord -scanbus<br /> # Cdrecord 1.10 (i686-pc-linux-gnu) Copyright (C) 1995-2001 J\F6rg Schilling<br /> # Linux sg driver version: 3.1.22<br /> # Using libscg version 'schily-0.5'<br /> # scsibus0:<br /> # 0,0,0 0) 'IOMEGA ' 'ZIP 100 ' '13.A' Removable Disk<br /> # 0,1,0 1) 'HP ' 'CD-Writer+ 8100 ' '1.0g' Removable CD-ROM<br /> # 0,2,0 2) *<br /> # 0,3,0 3) *<br /> # 0,4,0 4) *<br /> # 0,5,0 5) *<br /> # 0,6,0 6) *<br /> # 0,7,0 7) *<br /> #<br /> # I chose dev=0,1,0. speed can also be adjusted to suit your needs.<br /> cdrecord -v -data dev=0,1,0 speed=8 $1<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/change_name ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/change_name<br /> <code><br /> #!/bin/bash</p> <p>search=`gdialog --title "Rename files" --inputbox "Search for" 200 450 2>&1` || exit<br /> replace=`gdialog --title "Rename files" --inputbox "Replace with" 200 450 2>&1` || exit</p> <p>path=`echo -n "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | head -n 1 | sed 's/[^\/]*$//'`</p> <p>while [ $# -gt 0 ]; do<br /> newname=`echo "$1" | sed -e "s/$search/$replace/g"`<br /> mv "$path$1" "$path$newname"<br /> shift<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/chmod ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/chmod<br /> <code><br /> #!/usr/bin/perl<br /> #<br /> # A GUI for chown, chgrp and chmod. Requires perl and perl-gtk<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Copyright (C) David Westlund <daw@wlug.westbo.se><br /> #</p> <p>my $false = 0;<br /> my $true = 1;</p> <p>use Gtk;<br /> init Gtk;</p> <p># Widgets<br /> my $window;<br /> my $signal;<br /> my $main_vbox;</p> <p>my $user_table_alignment;<br /> my $user_table;<br /> my $user_label;<br /> my $user_entry;<br /> my $group_label;<br /> my $group_entry;</p> <p>my $separator1;</p> <p>my $chmod_table_alignment;<br /> my $chmod_table;</p> <p>my $user_chmod_label_alignment;<br /> my $user_chmod_label;<br /> my $group_chmod_label_alignment;<br /> my $group_chmod_label;<br /> my $others_chmod_label_alignment;<br /> my $others_chmod_label;</p> <p>my $read_label;<br /> my $user_read_button;<br /> my $group_read_button;<br /> my $others_read_button;</p> <p>my $write_label;<br /> my $user_write_button;<br /> my $group_write_button;<br /> my $others_write_button;</p> <p>my $execute_label;<br /> my $user_execute_button;<br /> my $group_execute_button;<br /> my $others_execute_button;</p> <p>my $separator2;</p> <p>my $file_info_hbox_alignment;<br /> my $file_info_hbox;<br /> my $permission_vbox;<br /> my @permissions;<br /> my $owner_vbox;<br /> my @owners_alignment;<br /> my @owners;<br /> my $group_vbox;<br /> my @groups_alignment;<br /> my @groups;<br /> my $filename_vbox;<br /> my @filenames_alignment;<br /> my @filenames;<br /> # Non-widgets (used in the ls-loop)<br /> my $file_info;<br /> my $rights;<br /> my $name;</p> <p>my $separator3;</p> <p>my $last_hbox;<br /> my $ok_button;<br /> my $cancel_button;</p> <p># Not widgets...<br /> my $id;<br /> my $user;<br /> #my @groups;</p> <p># Fix info about the user and the groups<br /> $id = `id`;<br /> $user = $id;<br /> $user =~ s/^[^\(]+\(//;<br /> $user =~ s/\).*//s;</p> <p># I don't use the code for groups now, but it may be handy<br /> # in the future...<br /> #@groups = split ",", $id;<br /> #$groups[0] =~ s/.*gid[^\(]+\(.*\(//;<br /> #$groups[0] =~ s/\).*//;</p> <p>#foreach (@groups) {<br /> #$_ =~ s/.*\(//;<br /> #$_ =~ s/\).*//s;<br /> #}</p> <p># Create the gtk-program<br /> $window = new Gtk::Window ( 'toplevel' );<br /> $signal = $window->signal_connect ('delete_event',<br /> sub { Gtk->exit (0); } );</p> <p>$window->border_width (5);<br /> $window->set_title ("Chmod");</p> <p>$main_vbox = new Gtk::VBox ($false, 0);<br /> $window->add ($main_vbox);<br /> $main_vbox->show ();</p> <p># The table for owners and groups.<br /> $user_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);<br /> $user_table = new Gtk::Table (2, 2, $true);<br /> $user_table_alignment->add ($user_table);<br /> $main_vbox->pack_start ($user_table_alignment, $false, $false, 0);<br /> $user_table_alignment->show ();<br /> $user_table->show ();</p> <p># Create the owners and groups row.<br /> if ($user =~ /^root$/) {<br /> $user_label = new Gtk::Label ("owner: ");<br /> $user_table->attach ($user_label, 0, 1, 0, 1, "fill", 0, 0, 0);<br /> $user_label->show ();</p> <p> $user_entry = new Gtk::Entry ( 10 );<br /> $user_entry->set_usize (60, undef);</p> <p> $user_table->attach ($user_entry, 1, 2, 0, 1, "fill", 0, 0, 0);<br /> $user_entry->show ();<br /> }</p> <p>$group_label = new Gtk::Label ("group: ");<br /> $user_table->attach ($group_label, 0, 1, 1, 2, "fill", 0, 0, 0);<br /> $group_label->show ();</p> <p>$group_entry = new Gtk::Entry ( 10 );<br /> $group_entry->set_usize (60, undef);<br /> $user_table->attach ($group_entry, 1, 2, 1, 2, "fill", 0, 0, 0);<br /> $group_entry->show ();</p> <p>$separator1 = new Gtk::HSeparator ();<br /> $main_vbox->pack_start ($separator1, $true, $true, 10);<br /> $separator1->show ();</p> <p># Time for the chmod-section<br /> $chmod_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);<br /> $chmod_table = new Gtk::Table (4, 4, $true);<br /> $chmod_table_alignment->add ($chmod_table);<br /> $main_vbox->pack_start ($chmod_table_alignment, $false, $false, 0);<br /> $chmod_table->set_col_spacings ( 0 );<br /> $chmod_table_alignment->show ();<br /> $chmod_table->show ();</p> <p># Adding the labels to the chmod_table<br /> $user_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);<br /> $user_chmod_label = new Gtk::Label ("user:");<br /> $user_chmod_label_alignment->add ($user_chmod_label);<br /> $chmod_table->attach ($user_chmod_label_alignment, 0, 1, 1, 2,"fill", 0, 0, 0);<br /> $user_chmod_label_alignment->show ();<br /> $user_chmod_label->show ();</p> <p>$group_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);<br /> $group_chmod_label = new Gtk::Label ("group:");<br /> $group_chmod_label_alignment->add ($group_chmod_label);<br /> $chmod_table->attach ($group_chmod_label_alignment,0, 1, 2, 3,"fill", 0, 0, 0);<br /> $group_chmod_label_alignment->show ();<br /> $group_chmod_label->show ();</p> <p>$others_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);<br /> $others_chmod_label = new Gtk::Label ("others:");<br /> $others_chmod_label_alignment->add ($others_chmod_label);<br /> $chmod_table->attach ($others_chmod_label_alignment,0, 1, 3, 4,"fill", 0, 0, 0);<br /> $others_chmod_label_alignment->show ();<br /> $others_chmod_label->show ();</p> <p># Adding the labels and the buttons to the read_vbox<br /> $read_label = new Gtk::Label ("read");<br /> $chmod_table->attach ($read_label, 1, 2, 0, 1, 0, 0, 0, 0);<br /> $read_label->show ();</p> <p>$user_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_read_button, 1, 2, 1, 2, 0, 0, 0, 0);<br /> $user_read_button->show ();</p> <p>$group_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_read_button, 1, 2, 2, 3, 0, 0, 0, 0);<br /> $group_read_button->show ();</p> <p>$others_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_read_button, 1, 2, 3, 4, 0, 0, 0, 0);<br /> $others_read_button->show ();</p> <p># Adding the labels and the buttons to the write_vbox<br /> $write_label = new Gtk::Label ("write");<br /> $chmod_table->attach ($write_label, 2, 3, 0, 1, 0, 0, 0, 0);<br /> $write_label->show ();</p> <p>$user_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_write_button, 2, 3, 1, 2, 0, 0, 0, 0);<br /> $user_write_button->show ();</p> <p>$group_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_write_button, 2, 3, 2, 3, 0, 0, 0, 0);<br /> $group_write_button->show ();</p> <p>$others_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_write_button, 2, 3, 3, 4, 0, 0, 0, 0);<br /> $others_write_button->show ();</p> <p># Adding the labels and the buttons to the execute_vbox<br /> $execute_label = new Gtk::Label ("execute");<br /> $chmod_table->attach ($execute_label, 3, 4, 0, 1, 0, 0, 0, 0);<br /> $execute_label->show ();</p> <p>$user_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_execute_button, 3, 4, 1, 2, 0, 0, 0, 0);<br /> $user_execute_button->show ();</p> <p>$group_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_execute_button, 3, 4, 2, 3, 0, 0, 0, 0);<br /> $group_execute_button->show ();</p> <p>$others_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_execute_button, 3, 4, 3, 4, 0, 0, 0, 0);<br /> $others_execute_button->show ();</p> <p>$separator2 = new Gtk::HSeparator ();<br /> $main_vbox->pack_start ($separator2, $true, $true, 10);<br /> $separator2->show ();</p> <p># Creating the list with filenames and permissions<br /> $file_info_hbox_alignment = new Gtk::Alignment (0.5,0,0,0);<br /> $file_info_hbox = new Gtk::HBox ($false, 0);<br /> $file_info_hbox_alignment->add ($file_info_hbox);<br /> $main_vbox->pack_start ($file_info_hbox_alignment, $false, $false, 0);<br /> $file_info_hbox_alignment->show ();<br /> $file_info_hbox->show ();</p> <p>$permission_vbox = new Gtk::VBox ($fase, 0);<br /> $file_info_hbox->pack_start ($permission_vbox, $false, $false, 20);<br /> $permission_vbox->show ();</p> <p>$owner_vbox = new Gtk::VBox ($false, 0);<br /> $file_info_hbox->pack_start ($owner_vbox, $false, $false, 10);<br /> $owner_vbox->show ();</p> <p>$group_vbox = new Gtk::VBox ($false, 0);<br /> $file_info_hbox->pack_start ($group_vbox, $false, $false, 10);<br /> $group_vbox->show ();</p> <p>$filename_vbox = new Gtk::VBox ($false, 0);<br /> $file_info_hbox->pack_start ($filename_vbox, $false, $false, 20);<br /> $filename_vbox->show ();</p> <p>$i = 0;<br /> foreach ( @ARGV ) {<br /> $file_info = `ls -ld \"$_\"`;<br /> chop $file_info;<br /> $rights = $file_info;<br /> $rights =~ s/\s.*//;<br /> $owner = $file_info;<br /> $owner =~ s/\S+\s+\S+\s+//;<br /> $owner =~ s/\s.*//;<br /> $group = $file_info;<br /> $group =~ s/\S+\s+\S+\s+\S+\s+//;<br /> $group =~ s/\s.*//;<br /> $name = $file_info;<br /> $name =~ s/\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+//;</p> <p> $permissions[$i] = new Gtk::Label ("$rights");<br /> $permission_vbox->pack_start ($permissions[$i], $false, $false, 0);<br /> $permissions[$i]->show ();</p> <p> $owners_alignment[$i] = new Gtk::Alignment (0,1,0,0);<br /> $owners[$i] = new Gtk::Label ("$owner");<br /> $owners_alignment[$i]->add ($owners[$i]);<br /> $owner_vbox->pack_start ($owners_alignment[$i],$false, $false, 0);<br /> $owners_alignment[$i]->show ();<br /> $owners[$i]->show ();</p> <p> $groups_alignment[$i] = new Gtk::Alignment (0,1,0,0);<br /> $groups[$i] = new Gtk::Label ("$group");<br /> $groups_alignment[$i]->add ($groups[$i]);<br /> $group_vbox->pack_start ($groups_alignment[$i],$false, $false, 0);<br /> $groups_alignment[$i]->show ();<br /> $groups[$i]->show ();</p> <p> $filenames_alignment[$i] = new Gtk::Alignment (0,1,0,0);<br /> $filenames[$i] = new Gtk::Label ("$name");<br /> $filenames_alignment[$i]->add ($filenames[$i]);<br /> $filename_vbox->pack_start ($filenames_alignment[$i],$false, $false, 0);<br /> $filenames_alignment[$i]->show ();<br /> $filenames[$i]->show ();<br /> $i++;<br /> }</p> <p>$separator3 = new Gtk::HSeparator ();<br /> $main_vbox->pack_start ($separator3, $true, $true, 10);<br /> $separator3->show ();</p> <p>#This is the last line of widgets in the program...<br /> $last_hbox = new Gtk::HBox ( $false, 0);<br /> $main_vbox->pack_start ($last_hbox, $false, $false, 5);<br /> $last_hbox->show ();</p> <p>$ok_button = new Gtk::Button ("Ok");<br /> $last_hbox->pack_start ($ok_button, $false, $false, 10);<br /> $ok_button->signal_connect ('clicked', \&chmod);<br /> $ok_button->show;</p> <p>$cancel_button = new Gtk::Button ("Cancel");<br /> $last_hbox->pack_start ($cancel_button, $false, $false, 10);<br /> $cancel_button->signal_connect ('clicked', sub { Gtk->exit (0) } );<br /> $cancel_button->show ();</p> <p>$window->show ();<br /> main Gtk;<br /> exit (1);</p> <p>sub chmod<br /> {<br /> my $mode = 0;<br /> my $recursive = "";<br /> my $files = "";</p> <p> $mode += 400 if $user_read_button->active;<br /> $mode += 200 if $user_write_button->active;<br /> $mode += 100 if $user_execute_button->active;<br /> $mode += 40 if $group_read_button->active;<br /> $mode += 20 if $group_write_button->active;<br /> $mode += 10 if $group_execute_button->active;<br /> $mode += 4 if $others_read_button->active;<br /> $mode += 2 if $others_write_button->active;<br /> $mode += 1 if $others_execute_button->active;</p> <p> $mode = "0" . $mode while length $mode < 3; foreach (@ARGV) { $files .= "\"$_\"" . " "; } system ("chmod $mode $files"); Gtk->exit ( 0 );<br /> }<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/chmog ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/chmog<br /> <code><br /> #!/usr/bin/perl<br /> #<br /> # A GUI for chown, chgrp and chmod. Requires perl and perl-gtk<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Copyright (C) David Westlund <daw@wlug.westbo.se><br /> #</p> <p>my $false = 0;<br /> my $true = 1;</p> <p>use Gtk;<br /> init Gtk;</p> <p># Widgets<br /> my $window;<br /> my $signal;<br /> my $main_vbox;</p> <p>my $user_table_alignment;<br /> my $user_table;<br /> my $user_label;<br /> my $user_entry;<br /> my $group_label;<br /> my $group_entry;</p> <p>my $separator1;</p> <p>my $chmod_table_alignment;<br /> my $chmod_table;</p> <p>my $user_chmod_label_alignment;<br /> my $user_chmod_label;<br /> my $group_chmod_label_alignment;<br /> my $group_chmod_label;<br /> my $others_chmod_label_alignment;<br /> my $others_chmod_label;</p> <p>my $read_label;<br /> my $read_plus_label;<br /> my $read_minus_label;<br /> my $user_plus_read_button;<br /> my $user_minus_read_button;<br /> my $group_plus_read_button;<br /> my $group_minus_read_button;<br /> my $others_plus_read_button;<br /> my $others_minus_read_button;</p> <p>my $write_label;<br /> my $write_plus_label;<br /> my $write_minus_label;<br /> my $user_plus_write_button;<br /> my $user_minus_write_button;<br /> my $group_plus_write_button;<br /> my $group_minus_write_button;<br /> my $others_plus_write_button;<br /> my $others_minus_write_button;</p> <p>my $execute_label;<br /> my $execute_plus_label;<br /> my $execute_minus_label;<br /> my $user_plus_execute_button;<br /> my $user_minus_execute_button;<br /> my $group_plus_execute_button;<br /> my $group_minus_execute_button;<br /> my $others_plus_execute_button;<br /> my $others_minus_execute_button;</p> <p>my $separator2;</p> <p>my $file_info_hbox_alignment;<br /> my $file_info_hbox;<br /> my $permission_vbox;<br /> my @permissions;<br /> my $owner_vbox;<br /> my @owners_alignment;<br /> my @owners;<br /> my $group_vbox;<br /> my @groups_alignment;<br /> my @groups;<br /> my $filename_vbox;<br /> my @filenames_alignment;<br /> my @filenames;<br /> # Non-widgets (used in the ls-loop)<br /> my $file_info;<br /> my $rights;<br /> my $name;</p> <p>my $separator3;</p> <p>my $last_hbox;<br /> my $recursice_button;<br /> my $ok_button;<br /> my $cancel_button;</p> <p># Not widgets...<br /> my $id;<br /> my $user;<br /> #my @groups;</p> <p># Fix info about the user and the groups<br /> $id = `id`;<br /> $user = $id;<br /> $user =~ s/^[^\(]+\(//;<br /> $user =~ s/\).*//s;</p> <p># I don't use the code for groups now, but it may be handy<br /> # in the future...<br /> #@groups = split ",", $id;<br /> #$groups[0] =~ s/.*gid[^\(]+\(.*\(//;<br /> #$groups[0] =~ s/\).*//;</p> <p>#foreach (@groups) {<br /> #$_ =~ s/.*\(//;<br /> #$_ =~ s/\).*//s;<br /> #}</p> <p># Create the gtk-program<br /> $window = new Gtk::Window ( 'toplevel' );<br /> $signal = $window->signal_connect ('delete_event',<br /> sub { Gtk->exit (0); } );</p> <p>$window->border_width (5);<br /> $window->set_title ("Chmog");</p> <p>$main_vbox = new Gtk::VBox ($false, 0);<br /> $window->add ($main_vbox);<br /> $main_vbox->show ();</p> <p># The table to put owner and group in<br /> $user_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);<br /> $user_table = new Gtk::Table (2, 2, $true);<br /> $user_table_alignment->add ($user_table);<br /> $main_vbox->pack_start ($user_table_alignment, $false, $false, 0);<br /> $user_table_alignment->show ();<br /> $user_table->show ();</p> <p># Create the owners and groups row.<br /> if ($user =~ /^root$/) {<br /> $user_label = new Gtk::Label ("owner: ");<br /> $user_table->attach ($user_label, 0, 1, 0, 1, "fill", 0, 0, 0);<br /> $user_label->show ();</p> <p> $user_entry = new Gtk::Entry ( 10 );<br /> $user_entry->set_usize (60, undef);</p> <p> $user_table->attach ($user_entry, 1, 2, 0, 1, "fill", 0, 0, 0);<br /> $user_entry->show ();<br /> }</p> <p>$group_label = new Gtk::Label ("group: ");<br /> $user_table->attach ($group_label, 0, 1, 1, 2, "fill", 0, 0, 0);<br /> $group_label->show ();</p> <p>$group_entry = new Gtk::Entry ( 10 );<br /> $group_entry->set_usize (60, undef);<br /> $user_table->attach ($group_entry, 1, 2, 1, 2, "fill", 0, 0, 0);<br /> $group_entry->show ();</p> <p>$separator1 = new Gtk::HSeparator ();<br /> $main_vbox->pack_start ($separator1, $true, $true, 10);<br /> $separator1->show ();</p> <p># Time for the chmod-section<br /> $chmod_table_alignment = new Gtk::Alignment (0.5, 0, 0, 0);<br /> $chmod_table = new Gtk::Table (5, 7, $true);<br /> $chmod_table_alignment->add ($chmod_table);<br /> $main_vbox->pack_start ($chmod_table_alignment, $false, $false, 0);<br /> $chmod_table->set_col_spacings ( 0 );<br /> $chmod_table_alignment->show ();<br /> $chmod_table->show ();</p> <p># Adding the labels to the chmod_table<br /> $user_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);<br /> $user_chmod_label = new Gtk::Label ("user:");<br /> $user_chmod_label_alignment->add ($user_chmod_label);<br /> $chmod_table->attach ($user_chmod_label_alignment, 0, 1, 2, 3,"fill", 0, 0, 0);<br /> $user_chmod_label_alignment->show ();<br /> $user_chmod_label->show ();</p> <p>$group_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);<br /> $group_chmod_label = new Gtk::Label ("group:");<br /> $group_chmod_label_alignment->add ($group_chmod_label);<br /> $chmod_table->attach ($group_chmod_label_alignment,0, 1, 3, 4,"fill", 0, 0, 0);<br /> $group_chmod_label_alignment->show ();<br /> $group_chmod_label->show ();</p> <p>$others_chmod_label_alignment = new Gtk::Alignment (1,0,0,0);<br /> $others_chmod_label = new Gtk::Label ("others:");<br /> $others_chmod_label_alignment->add ($others_chmod_label);<br /> $chmod_table->attach ($others_chmod_label_alignment,0, 1, 4, 5,"fill", 0, 0, 0);<br /> $others_chmod_label_alignment->show ();<br /> $others_chmod_label->show ();</p> <p># Adding the labels and the buttons to the read_vbox<br /> $read_label = new Gtk::Label ("read");<br /> $chmod_table->attach ($read_label, 1, 3, 0, 1, 0, 0, 0, 0);<br /> $read_label->show ();</p> <p>$read_plus_label = new Gtk::Label ("+");<br /> $chmod_table->attach ($read_plus_label, 1, 2, 1, 2, 0, 0, 0, 0);<br /> $read_plus_label->show ();</p> <p>$read_minus_label = new Gtk::Label ("-");<br /> $chmod_table->attach ($read_minus_label, 2, 3, 1, 2, 0, 0, 0, 0);<br /> $read_minus_label->show ();</p> <p>$user_plus_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_plus_read_button, 1, 2, 2, 3, 0, 0, 0, 0);<br /> $user_plus_read_button->show ();</p> <p>$user_minus_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_minus_read_button, 2, 3, 2, 3, 0, 0, 0, 0);<br /> $user_minus_read_button->show ();</p> <p>#callbacks<br /> $user_plus_read_button->signal_connect ("clicked", \&check_button_callback,<br /> $user_minus_read_button);<br /> $user_minus_read_button->signal_connect ("clicked", \&check_button_callback,<br /> $user_plus_read_button);</p> <p>$group_plus_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_plus_read_button, 1, 2, 3, 4, 0, 0, 0, 0);<br /> $group_plus_read_button->show ();</p> <p>$group_minus_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_minus_read_button, 2, 3, 3, 4, 0, 0, 0, 0);<br /> $group_minus_read_button->show ();</p> <p>#callbacks<br /> $group_plus_read_button->signal_connect ("clicked", \&check_button_callback,<br /> $group_minus_read_button);<br /> $group_minus_read_button->signal_connect ("clicked", \&check_button_callback,<br /> $group_plus_read_button);</p> <p>$others_plus_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_plus_read_button, 1, 2, 4, 5, 0, 0, 0, 0);<br /> $others_plus_read_button->show ();</p> <p>$others_minus_read_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_minus_read_button, 2, 3, 4, 5, 0, 0, 0, 0);<br /> $others_minus_read_button->show ();</p> <p>#callbacks<br /> $others_plus_read_button->signal_connect ("clicked", \&check_button_callback,<br /> $others_minus_read_button);<br /> $others_minus_read_button->signal_connect ("clicked", \&check_button_callback,<br /> $others_plus_read_button);</p> <p># Adding the labels and the buttons to the write_vbox<br /> $write_label = new Gtk::Label ("write");<br /> $chmod_table->attach ($write_label, 3, 5, 0, 1, 0, 0, 0, 0);<br /> $write_label->show ();</p> <p>$write_plus_label = new Gtk::Label ("+");<br /> $chmod_table->attach ($write_plus_label, 3, 4, 1, 2, 0, 0, 0, 0);<br /> $write_plus_label->show ();</p> <p>$write_minus_label = new Gtk::Label ("-");<br /> $chmod_table->attach ($write_minus_label, 4, 5, 1, 2, 0, 0, 0, 0);<br /> $write_minus_label->show ();</p> <p>$user_plus_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_plus_write_button, 3, 4, 2, 3, 0, 0, 0, 0);<br /> $user_plus_write_button->show ();</p> <p>$user_minus_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_minus_write_button, 4, 5, 2, 3, 0, 0, 0, 0);<br /> $user_minus_write_button->show ();</p> <p>#callbacks<br /> $user_plus_write_button->signal_connect ("clicked", \&check_button_callback,<br /> $user_minus_write_button);<br /> $user_minus_write_button->signal_connect ("clicked", \&check_button_callback,<br /> $user_plus_write_button);</p> <p>$group_plus_read_button = new Gtk::CheckButton ();<br /> $group_plus_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_plus_write_button, 3, 4, 3, 4, 0, 0, 0, 0);<br /> $group_plus_write_button->show ();</p> <p>$group_minus_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_minus_write_button, 4, 5, 3, 4, 0, 0, 0, 0);<br /> $group_minus_write_button->show ();</p> <p>#callbacks<br /> $group_plus_write_button->signal_connect ("clicked", \&check_button_callback,<br /> $group_minus_write_button);<br /> $group_minus_write_button->signal_connect ("clicked", \&check_button_callback,<br /> $group_plus_write_button);</p> <p>$others_plus_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_plus_write_button, 3, 4, 4, 5, 0, 0, 0, 0);<br /> $others_plus_write_button->show ();</p> <p>$others_minus_write_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_minus_write_button, 4, 5, 4, 5, 0, 0, 0, 0);<br /> $others_minus_write_button->show ();</p> <p>#callbacks<br /> $others_plus_write_button->signal_connect ("clicked", \&check_button_callback,<br /> $others_minus_write_button);<br /> $others_minus_write_button->signal_connect ("clicked", \&check_button_callback,<br /> $others_plus_write_button);</p> <p># Adding the labels and the buttons to the execute_vbox<br /> $execute_label = new Gtk::Label ("execute");<br /> $chmod_table->attach ($execute_label, 5, 7, 0, 1, 0, 0, 0, 0);<br /> $execute_label->show ();</p> <p>$execute_plus_label = new Gtk::Label ("+");<br /> $chmod_table->attach ($execute_plus_label, 5, 6, 1, 2, 0, 0, 0, 0);<br /> $execute_plus_label->show ();</p> <p>$execute_minus_label = new Gtk::Label ("-");<br /> $chmod_table->attach ($execute_minus_label, 6, 7, 1, 2, 0, 0, 0, 0);<br /> $execute_minus_label->show ();</p> <p>$user_plus_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_plus_execute_button, 5, 6, 2, 3, 0, 0, 0, 0);<br /> $user_plus_execute_button->show ();</p> <p>$user_minus_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($user_minus_execute_button, 6, 7, 2, 3, 0, 0, 0, 0);<br /> $user_minus_execute_button->show ();</p> <p>#callbacks<br /> $user_plus_execute_button->signal_connect ("clicked", \&check_button_callback,<br /> $user_minus_execute_button);<br /> $user_minus_execute_button->signal_connect ("clicked", \&check_button_callback,<br /> $user_plus_execute_button);</p> <p>$group_plus_read_button = new Gtk::CheckButton ();</p> <p>$group_plus_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_plus_execute_button, 5, 6, 3, 4, 0, 0, 0, 0);<br /> $group_plus_execute_button->show ();</p> <p>$group_minus_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($group_minus_execute_button, 6, 7, 3, 4, 0, 0, 0, 0);<br /> $group_minus_execute_button->show ();</p> <p>#callbacks<br /> $group_plus_execute_button->signal_connect ("clicked", \&check_button_callback,<br /> $group_minus_execute_button);<br /> $group_minus_execute_button->signal_connect ("clicked", \&check_button_callback,<br /> $group_plus_execute_button);</p> <p>$others_plus_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_plus_execute_button, 5, 6, 4, 5, 0, 0, 0, 0);<br /> $others_plus_execute_button->show ();</p> <p>$others_minus_execute_button = new Gtk::CheckButton ();<br /> $chmod_table->attach ($others_minus_execute_button, 6, 7, 4, 5, 0, 0, 0, 0);<br /> $others_minus_execute_button->show ();</p> <p>#callbacks<br /> $others_plus_execute_button->signal_connect ("clicked", \&check_button_callback,<br /> $others_minus_execute_button);<br /> $others_minus_execute_button->signal_connect ("clicked",\&check_button_callback,<br /> $others_plus_execute_button);</p> <p>$separator2 = new Gtk::HSeparator ();<br /> $main_vbox->pack_start ($separator2, $true, $true, 10);<br /> $separator2->show ();</p> <p># Creating the list with filenames and permissions<br /> $file_info_hbox_alignment = new Gtk::Alignment (0.5,0,0,0);<br /> $file_info_hbox = new Gtk::HBox ($false, 0);<br /> $file_info_hbox_alignment->add ($file_info_hbox);<br /> $main_vbox->pack_start ($file_info_hbox_alignment, $false, $false, 0);<br /> $file_info_hbox_alignment->show ();<br /> $file_info_hbox->show ();</p> <p>$permission_vbox = new Gtk::VBox ($fase, 0);<br /> $file_info_hbox->pack_start ($permission_vbox, $false, $false, 20);<br /> $permission_vbox->show ();</p> <p>$owner_vbox = new Gtk::VBox ($false, 0);<br /> $file_info_hbox->pack_start ($owner_vbox, $false, $false, 10);<br /> $owner_vbox->show ();</p> <p>$group_vbox = new Gtk::VBox ($false, 0);<br /> $file_info_hbox->pack_start ($group_vbox, $false, $false, 10);<br /> $group_vbox->show ();</p> <p>$filename_vbox = new Gtk::VBox ($false, 0);<br /> $file_info_hbox->pack_start ($filename_vbox, $false, $false, 20);<br /> $filename_vbox->show ();</p> <p>$i = 0;<br /> foreach ( @ARGV ) {<br /> $file_info = `ls -ld \"$_\"`;<br /> chop $file_info;<br /> $rights = $file_info;<br /> $rights =~ s/\s.*//;<br /> $owner = $file_info;<br /> $owner =~ s/\S+\s+\S+\s+//;<br /> $owner =~ s/\s.*//;<br /> $group = $file_info;<br /> $group =~ s/\S+\s+\S+\s+\S+\s+//;<br /> $group =~ s/\s.*//;<br /> $name = $file_info;<br /> $name =~ s/\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+//;</p> <p> $permissions[$i] = new Gtk::Label ("$rights");<br /> $permission_vbox->pack_start ($permissions[$i], $false, $false, 0);<br /> $permissions[$i]->show ();</p> <p> $owners_alignment[$i] = new Gtk::Alignment (0,1,0,0);<br /> $owners[$i] = new Gtk::Label ("$owner");<br /> $owners_alignment[$i]->add ($owners[$i]);<br /> $owner_vbox->pack_start ($owners_alignment[$i],$false, $false, 0);<br /> $owners_alignment[$i]->show ();<br /> $owners[$i]->show ();</p> <p> $groups_alignment[$i] = new Gtk::Alignment (0,1,0,0);<br /> $groups[$i] = new Gtk::Label ("$group");<br /> $groups_alignment[$i]->add ($groups[$i]);<br /> $group_vbox->pack_start ($groups_alignment[$i],$false, $false, 0);<br /> $groups_alignment[$i]->show ();<br /> $groups[$i]->show ();</p> <p> $filenames_alignment[$i] = new Gtk::Alignment (0,1,0,0);<br /> $filenames[$i] = new Gtk::Label ("$name");<br /> $filenames_alignment[$i]->add ($filenames[$i]);<br /> $filename_vbox->pack_start ($filenames_alignment[$i],$false, $false, 0);<br /> $filenames_alignment[$i]->show ();<br /> $filenames[$i]->show ();<br /> $i++;<br /> }</p> <p>$separator3 = new Gtk::HSeparator ();<br /> $main_vbox->pack_start ($separator3, $true, $true, 10);<br /> $separator3->show ();</p> <p>#This is the last line of widgets in the program...<br /> $last_hbox = new Gtk::HBox ( $false, 0);<br /> $main_vbox->pack_start ($last_hbox, $false, $false, 5);<br /> $last_hbox->show ();</p> <p>$recursive_button = new Gtk::CheckButton ("Change recursive");<br /> $last_hbox->pack_start ($recursive_button, $false, $false, 10);<br /> $recursive_button->show ();</p> <p>$ok_button = new Gtk::Button ("Ok");<br /> $last_hbox->pack_start ($ok_button, $false, $false, 10);<br /> $ok_button->signal_connect ('clicked', \&chmod);<br /> $ok_button->show;</p> <p>$cancel_button = new Gtk::Button ("Cancel");<br /> $last_hbox->pack_start ($cancel_button, $false, $false, 10);<br /> $cancel_button->signal_connect ('clicked', sub { Gtk->exit (0) } );<br /> $cancel_button->show ();</p> <p>$window->show ();<br /> main Gtk;<br /> exit (1);</p> <p>sub check_button_callback<br /> {<br /> $button1 = $_[0];<br /> $button2 = $_[1];</p> <p> $button2->set_active ($false) if $button1->get_active;<br /> }</p> <p>sub chmod<br /> {<br /> my $mode = 0;<br /> my $recursive = "";<br /> my $files = "";<br /> my $new_group = $group_entry->get_text ();<br /> my $upmode = "u+";<br /> my $ummode = "u-";<br /> my $gpmode = "g+";<br /> my $gmmode = "g-";<br /> my $opmode = "o+";<br /> my $ommode = "o-";</p> <p> $upmode .= "r" if $user_plus_read_button->active;<br /> $upmode .= "w" if $user_plus_write_button->active;<br /> $upmode .= "x" if $user_plus_execute_button->active;<br /> $ummode .= "r" if $user_minus_read_button->active;<br /> $ummode .= "w" if $user_minus_write_button->active;<br /> $ummode .= "x" if $user_minus_execute_button->active;<br /> $gpmode .= "r" if $group_plus_read_button->active;<br /> $gpmode .= "w" if $group_plus_write_button->active;<br /> $gpmode .= "x" if $group_plus_execute_button->active;<br /> $gmmode .= "r" if $group_minus_read_button->active;<br /> $gmmode .= "w" if $group_minus_write_button->active;<br /> $gmmode .= "x" if $group_minus_execute_button->active;<br /> $opmode .= "r" if $others_plus_read_button->active;<br /> $opmode .= "w" if $others_plus_write_button->active;<br /> $opmode .= "x" if $others_plus_execute_button->active;<br /> $ommode .= "r" if $others_minus_read_button->active;<br /> $ommode .= "w" if $others_minus_write_button->active;<br /> $ommode .= "x" if $others_minus_execute_button->active;<br /> $recursive = "-R" if $recursive_button->active;<br /> $recursive = "-R" if $recursive_button->active;</p> <p> $upmode = "" if $umode =~ /^u\+$/;<br /> $ummode = "" if $umode =~ /^u\-$/;<br /> $gpmode = "" if $gmode =~ /^g\+$/;<br /> $gmmode = "" if $gmode =~ /^g\-$/;<br /> $opmode = "" if $omode =~ /^o\+$/;<br /> $ommode = "" if $omode =~ /^o\-$/;</p> <p> foreach (@ARGV) {<br /> $files .= "\"$_\"" . " ";<br /> }</p> <p> system ("chmod $recursive $upmode,$gpmode,$opmode,$ummode,$gmmode,$ommode $files");</p> <p> if ($user eq "root") {<br /> my $new_user = $user_entry->get_text ();<br /> system ("chown $recursive $new_user $files") if $new_user =~ /\w+/;<br /> }</p> <p> system ("chgrp $recursive $new_group $files") if $new_group =~ /\w+/;</p> <p> Gtk->exit ( 0 );<br /> }<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/copyhome ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/copyhome<br /> <code><br /> #!/bin/sh<br /> # copyhome: copies the selected file(s) to home directory<br /> # (if able)</p> <p>for arg<br /> do<br /> if [ -f ~/"$arg" ]; then<br /> MSG="File: '$arg' already exists in home directory. Overwrite?"<br /> if<br /> gdialog --title "Overwrite?" --defaultno --yesno "$MSG" 200 100 </p> <p> then<br /> cp "$arg" ~/"$arg"<br /> fi<br /> else<br /> cp "$arg" ~/"$arg"<br /> fi</p> <p>done</code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/Get_Photos ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/Get_Photos<br /> <code><br /> #!/usr/bin/perl -w<br /> # Created: Wed Dec 26 19:46:59 2001<br /> # Last modified: Wed Dec 26 20:35:47 2001<br /> # Time-stamp: <01/12/26 20:35:47 nevin></p> <p>## Copyright (C) 2001 by Nevin Kapur</p> <p>## Author: Nevin Kapur <nevin@jhu.edu></p> <p>## This is free software; you can redistribute it and/or modify it<br /> ## under the terms of the GNU General Public License as published by<br /> ## the Free Software Foundation; either version 2, or (at your option)<br /> ## any later version.</p> <p>## This is distributed in the hope that it will be useful, but<br /> ## WITHOUT ANY WARRANTY; without even the implied warranty of<br /> ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU<br /> ## General Public License for more details.</p> <p>## Get photos from a digital camera. This script is meant to be run on<br /> ## a selected directory. It will silently fail till I get around to<br /> ## playing with gdialog.</p> <p>## How to run gphoto; By default, this script will transfer everything<br /> ## on the default camera to the first selected directory. (I haven't<br /> ## experimented with what Nautilus thinks is the "first" directory if<br /> ## more that one directory is selected.)</p> <p>my $GPHOTO = q[/usr/bin/gphoto2];<br /> my @GPHOTO_OPTIONS = qw[ -q -P ];</p> <p>## It is a shame that the scripts menu does not become active unless<br /> ## something is selected, otherwise we could have a version where the<br /> ## images would be magically appear in the current directory;</p> <p>## It would be nice if one could assume the existence of these<br /> ## modules, but they are not bundled with Perl<br /> ## use URI;<br /> ## use URI::Escape;</p> <p>## Silently discard the output if more that one directory is selected<br /> my $uri = (split "\n", $ENV{NAUTILUS_SCRIPT_SELECTED_URIS})[0];</p> <p>## Hack, hack, hack;<br /> $uri =~ s[^file://][];</p> <p>## From the URI::Escape man page:<br /> $uri =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;</p> <p>## Only execute if what we got was a directory<br /> if (-d $uri) {<br /> chdir $uri or die;<br /> system $GPHOTO, @GPHOTO_OPTIONS;<br /> }</p> <p>__END__</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/junksorter ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/junksorter<br /> <code></p> <p>#!/bin/bash<br /> ################################################################################<br /> ## Script: junksorter<br /> ## Author: Unknown<br /> ## Date: Unknown<br /> ## Category: File Utilities<br /> ################################################################################<br /> ## Description: This script will automatically sort files for you, into whatever<br /> ## directories you want, under a root-level 'junk'directory. For<br /> ## seamless integration, make this ~/.junk and symlink directories<br /> ## in there. Includes detection of mp3s (requires mp3info), images,<br /> ## movies, text and pdf documents, and various other stuff.<br /> ################################################################################<br /> ## Changes<br /> ## Author: Brian Pepple <bdpepple@ameritech.net><br /> ## 09.06.2003 Modified mp3 section, and various clean-up.<br /> ##<br /> ## Author: Vittorio Colao <vittorio(at)noldor.zapto.org><br /> ## 26.12.2003 Added mp3 detection.<br /> ## 04.02.2004 Made it working under nautilus-2.x<br /> ################################################################################<br /> ## The home directory may need to be changed to a hard-coded path.<br /> junk= ~/junk</p> <p>msg="already exists in"<br /> overwrite="Overwrite?"<br /> file="File: "</p> <p>for arg in $(echo $NAUTILUS_SCRIPT_SELECTED_URIS|sed 's/file:\/\///');<br /> do<br /> artist="misc"<br /> album="."<br /> new_artist=""<br /> new_album="" </p> <p> filename="$arg"<br /> filetype=`file -b "$filename"`</p> <p> if [ -n "`echo $filetype | grep -i 'image' `" ]; then<br /> dest="$junk/images/"</p> <p> elif [ -n "`echo $filetype | grep -i 'rpm' `" ]; then<br /> dest="$junk/rpms/"</p> <p> elif [ -n "`echo $filename | grep -i 'svg' `" ]; then<br /> dest="$junk/images/"</p> <p> elif [ -n "`echo $filetype | grep -i 'audio' `" ]; then<br /> dest="$junk/audio/"</p> <p> elif [ -n "`echo $filename | grep -i 'MPG' `" ]; then<br /> dest="$junk/video/"</p> <p> elif [ -n "`echo $filetype | grep -i 'MPEG' `" ]; then<br /> dest="$junk/video/"</p> <p> elif [ -n "`echo $filetype | grep -i 'AVI' `" ]; then<br /> dest="$junk/video/"</p> <p> elif [ -n "`echo $filetype | grep -i 'pdf' `" ]; then<br /> dest="$junk/documents/"</p> <p> elif [ -n "`echo $filetype | grep -i 'PostScript' `" ]; then<br /> dest="$junk/documents/"</p> <p> elif [ -n "`echo $filetype | grep -i 'Microsoft Office Document' `" ];<br /> then<br /> dest="$junk/documents/"</p> <p> elif [ -n "`echo $filetype | grep -i 'Rich Text Format' `" ]; then<br /> dest="$junk/documents/"</p> <p> elif [ -n "`echo $filetype | grep 'TeX' `" ]; then<br /> dest="$junk/documents/"</p> <p> elif [ -n "`echo $filename | grep 'TeX' `" ]; then<br /> dest="$junk/documents/"</p> <p> elif [ -n "`echo $filetype | grep -i 'zip' `" ]; then<br /> dest="$junk/archives/"</p> <p> elif [ -n "`echo $filetype | grep -i 'script'`" ]; then<br /> dest="$junk/text/scripts/"</p> <p> elif [ -n "`echo $filetype | grep -i 'text' `" ]; then<br /> dest="$junk/text/"</p> <p> elif [ -n "`echo $filetype | grep -i 'MP3' `" ]; then<br /> new_artist="`mp3info -p "%a" "$filename"`"<br /> new_album="`mp3info -p "%l" "$filename"`"</p> <p> if [ ! -d "$junk/mp3" ]; then<br /> mkdir -p "$junk/mp3"<br /> fi<br /> if [ -n "$new_artist" ]; then<br /> artist="$new_artist"<br /> if [ ! -d "$junk/mp3/$artist" ]; then<br /> mkdir -p "$junk/mp3/$artist"<br /> fi<br /> fi<br /> if [ -n "$new_album" ]; then<br /> album="$new_album"<br /> if [ ! -d "$junk/mp3/$artist/$album" ]; then<br /> mkdir -p "$junk/mp3/$artist/$album"<br /> fi<br /> fi<br /> dest="$junk/mp3/$artist/$album/"<br /> else<br /> dest="$junk/misc/"<br /> fi</p> <p>#Now, create the destination directory if it doesn't exist<br /> if [ ! -d $dest ]; then<br /> mkdir -p "$dest"<br /> fi</p> <p>#Finally, move the file to the destination (if it doesn't exist there)<br /> if [ -f "$dest$filename" ]; then<br /> if gdialog --title "Overwrite?" --defaultno --yesno "$file<br /> $filename $msg $dest $overwrite" 4 100; then<br /> mv "$filename" "$dest"<br /> fi<br /> else<br /> mv "$filename" "$dest"<br /> fi<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/Junksorter.pl ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/Junksorter.pl<br /> <code><br /> #!/usr/bin/perl -w</p> <p>#########################################################################################<br /> # Nautilus script for sorting home directory files.<br /> #########################################################################################<br /> #<br /> # NAME: junksorter.pl<br /> #<br /> # AUTHOR: Brian Pepple <bdpepple@ameritech.net><br /> #<br /> # DESCRIPTION: This script sorts the selected files based on the Mime<br /> # information, and moves the file to the appropriate<br /> # folder. It will also sort mp3's based on the information<br /> # contained within their ID3 tag.<br /> #<br /> # REQUIREMENTS: Nautilus file manager<br /> # Zenity, which replaces the venerable gdialog.<br /> # Shared Mime Info-0.12 : available at<br /> # http://freedesktop.org/Software/shared-mime-info<br /> # Perl >= 5.8<br /> # Perl Modules: MP3::Tag, File::Copy, File::MimeInfo<br /> #<br /> # INSTALLATION: GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory,<br /> #<br /> # USAGE: Select the files that you would like to sort in Nautilus,<br /> # right click, go to Scripts, and then select this script.<br /> # IF the file being moved would overwrite an existing file,<br /> # a dialog window will appear giving you the option to cancel<br /> # the action for that file.<br /> #<br /> # VERSION INFO: 0.8 (20031224) - Merged some switch cases, to reduce<br /> # number of switches needed, and speed<br /> # up script.<br /> # 0.7 (20031220) - Cleaned up switch statement.<br /> # 0.6 (20031216) - Use enviroments $HOME value, instead of<br /> # hard-coding the path.<br /> # 0.5 (20031212) - Added hack that will allow files on the<br /> # users desktop to be handled correctly.<br /> # If a directory is accidently selected the<br /> # script will not move it.<br /> # 0.4 (20031129) - Changed base location to default home,<br /> # this will make it play better with the<br /> # spatial version of Nautilus, that is in<br /> # Gnome >= 2.5.0. Also, added some error<br /> # checking.<br /> # 0.3 (20031128) - Replaced folder creation loop, and some<br /> # minor clean up.<br /> # 0.2 (20031127) - Added quick hack to add base folder. Will<br /> # clean this in later version.<br /> # 0.1 (20031126) - Initial public release<br /> #<br /> # COPYRIGHT: Copyright (C) 2003 Brian Pepple <bdpepple@ameritech.net><br /> #<br /> # LICENSE: GNU GPL<br /> #<br /> #########################################################################################</p> <p>use MP3::Tag;<br /> use File::Basename qw(basename);<br /> use File::Copy qw(move);<br /> use File::MimeInfo qw(mimetype);<br /> use Switch;</p> <p>use strict;</p> <p>$|++; # Turn on autoflush</p> <p>#########################################################################################<br /> ## EDIT THIS to suit your needs.<br /> ##<br /> ## Directory paths.<br /> my $home = $ENV{'HOME'};<br /> my $rpm = $home . '/rpms/';<br /> my $deb = $home . '/debs/';<br /> my $video = $home . '/video/';<br /> my $iso = $home . '/iso/';<br /> my $image = $home . '/images/';<br /> my $document = $home . '/documents/'; # If you are using Ximian<br /> # change to 'Documents'<br /> my $spreadsheet = $document . 'spreadsheets/';<br /> my $webpage = $document . 'web/';<br /> my $script = $document . 'scripts/';<br /> my $template = $document . 'templates/';<br /> my $font = $home . '/fonts/';<br /> my $music = $home . '/music/';<br /> my $archive = $home . '/archives/';</p> <p>#########################################################################################<br /> sub makedir {<br /> my $directory = (shift or "");</p> <p> # If directory already exist stop subroutine.<br /> return if -d $directory;</p> <p> mkdir $directory, 0700<br /> or die "Problem creating directory $directory: $!\n";<br /> }</p> <p>sub taginfo {<br /> my $artist;<br /> my $album;<br /> my $temppath;</p> <p> # Create path information from ID3 tag.<br /> my $mp3 = MP3::Tag->new(@_);<br /> $mp3->get_tags;<br /> if (exists $mp3->{ID3v1}) {<br /> my $id3v1 = $mp3->{ID3v1};<br /> $artist = $id3v1->artist;<br /> $album = $id3v1->album;<br /> $temppath = $music . "$artist/$album/";<br /> } elsif (exists $mp3->{ID3v2}) {<br /> my $id3v2 = $mp3->{ID3v2};<br /> $artist = $id3v2->artist;<br /> $album = $id3v2->album;<br /> $temppath = $music . "$artist/$album/";<br /> } else {<br /> $artist = "misc";<br /> $temppath = $music . "$artist/";<br /> }<br /> $mp3->close();</p> <p> # Create folders for music files.<br /> my @folders = ($music, $music . $artist, $temppath);</p> <p> foreach (@folders) {<br /> unless (-d ($_)) {<br /> makedir ($_);<br /> }<br /> }</p> <p> return $temppath;<br /> }</p> <p>#########################################################################################<br /> ## MAIN LOGIC<br /> #########################################################################################</p> <p># If no file selected tell the user, and stop the script.<br /> if (!@ARGV) {<br /> system "zenity", "--info", "--title", "No Files Selected", "--text",<br /> "Unable to run junksorter.pl No files were selected.";<br /> exit;<br /> }</p> <p>foreach (@ARGV) {<br /> # Starting variables.<br /> my $file;<br /> my $dir = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'};<br /> my $base = basename ($_);<br /> my $mime = mimetype($_);<br /> my $dest;</p> <p> #system "zenity", "--info", "--title", "Debug", "--text",<br /> #"Dir: $dir\nBase: $base\nMime: $mime";<br /> #exit;</p> <p> # Ugly hack to determine if the script is being ran from the Desktop.<br /> if ($dir =~ /x-nautilus-desktop/) {<br /> $file = $home . "/Desktop/" . $base;<br /> } else {<br /> if ($dir =~ /file:\/\/\//) {<br /> $dir =~ s/file:\/\///;<br /> $file = $dir . '/' . $base;<br /> } else {<br /> system "zenity", "--info", "--title", "Error", "--text",<br /> "Unable to move selected file. $dir is not a valid path.";<br /> exit;<br /> }<br /> }</p> <p> # Start of switch statement, which determines the file type,<br /> # and determines where file should be moved. If type isn't here,<br /> # the file is move to $home/misc/ folder.<br /> switch ($mime) {<br /> case /video/ {$dest = $video}<br /> case /image/ {$dest = $image}<br /> case /audio/ {$dest = &taginfo($file)}<br /> case /perl/ {$dest = $script; &makedir($document)}<br /> case /x-python/ {$dest = $script; &makedir($document)}<br /> case /x-ruby/ {$dest = $script; &makedir($document)}<br /> case /x-shellscript/ {$dest = $script; &makedir($document)}<br /> case /x-tar/ {$dest = $archive}<br /> case /x-gtar/ {$dest = $archive}<br /> case /x-bzip/ {$dest = $archive}<br /> case /x-bzip-compressed-tar/ {$dest = $archive}<br /> case /x-compress/ {$dest = $archive}<br /> case /x-compressed-tar/ {$dest = $archive}<br /> case /x-gzip/ {$dest = $archive}<br /> case /zip/ {$dest = $archive}<br /> case /word/ {$dest = $document}<br /> case /pdf/ {$dest = $document}<br /> case /pgp/ {$dest = $document}<br /> case /postscript/ {$dest = $document}<br /> case /rtf/ {$dest = $document}<br /> case /ms-excel/ {$dest = $spreadsheet; &makedir($document)}<br /> case /ms-powerpoint/ {$dest = $document}<br /> case /ms-word/ {$dest = $document}<br /> case /html/ {$dest = $webpage; &makedir($document)}<br /> case /x-php/ {$dest = $webpage; &makedir($document)}<br /> case /css/ {$dest = $webpage; &makedir($document)}<br /> case /calc/ {$dest = $spreadsheet; &makedir($document)}<br /> case /draw/ {$dest = $spreadsheet; &makedir($document)}<br /> case /template/ {$dest = $template; &makedir($document)}<br /> case /impress/ {$dest = $document}<br /> case /math/ {$dest = $spreadsheet; &makedir($document)}<br /> case /writer/ {$dest = $document}<br /> case /x-amipro/ {$dest = $document}<br /> case /stardivision.chart/ {$dest = $document}<br /> case /stardivision.mail/ {$dest = $document}<br /> case /x-asp/ {$dest = $webpage; &makedir($document)}<br /> case /x-cd-image/ {$dest = $iso}<br /> case /x-cgi/ {$dest = $webpage; &makedir($document)}<br /> case /x-dia-diagram/ {$dest = $document}<br /> case /font/ {$dest = $font}<br /> case /x-gnumeric/ {$dest = $spreadsheet; &makedir($document)}<br /> case /x-jar/ {$dest = $archive}<br /> case /x-rpm/ {$dest = $rpm}<br /> case /x-deb/ {$dest = $deb}<br /> case /x-mswrite/ {$dest = $document}<br /> case /x-rar/ {$dest = $archive}<br /> else {$dest = $home . '/misc/'}<br /> }</p> <p> # Create folders if they don't already exist.<br /> my @global_folders = ($dest);</p> <p> foreach (@global_folders) {<br /> unless (-d ($_)) {<br /> makedir ($_);<br /> }<br /> }</p> <p> # Move the select files to appropriate folder,<br /> # ignoring any folders accidently selected.<br /> unless (-d $file) {<br /> if (-e $dest . $base) {<br /> # Ask the user if he wishes to overwrite file that already exists.<br /> my $overwrite = system "zenity", "--question", "--title",<br /> "File Exists", "--text",<br /> "$base already exists in $dest. Do you want to overwrite it?";</p> <p> # Zenity --question will return 0 when the user presses OK.<br /> if ($overwrite == 0) {<br /> move ($file, $dest . $base);<br /> }<br /> } else {<br /> move ($file, $dest . $base);<br /> }<br /> }<br /> }<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/linker ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/linker<br /> <code><br /> #!/bin/sh<br /> #Linker...Creates a link into your home directory<br /> # With thanks to Doug Nordwall<br /> for arg<br /> do<br /> ln -s $PWD/$arg ~/$arg<br /> done</code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/lowercase ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/lowercase<br /> <code><br /> #!/bin/sh<br /> # lowercase: Changes input to lowercase.<br /> for arg<br /> do<br /> tmp=`echo "$arg" | tr '[A-Z]' '[a-z]'`</p> <p> if [ -f $tmp ]<br /> then<br /> msg="Lowercase filename: '$tmp' already exists."<br /> gdialog --msgbox "$msg" 100 100<br /> else<br /> mv "$arg" "$tmp"<br /> fi<br /> done</code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/Make_Link ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/Make_Link<br /> <code><br /> #!/bin/sh<br /> #<br /> # Nautilus script that links selected files to desktop.<br /> #<br /> # Author: Krzysztof Luks <m00se@iq.pl><br /> #<br /> # Copyright (C) 2002 Krzysztof Luks<br /> # Licence: GNU GPL<br /> #<br /> # Dependency: nautilus and ln ;)<br /> #</p> <p>DESKTOP="$HOME/.gnome-desktop"</p> <p># We don't want to split NAUTILUS_SCRIPT_SELECTED_FILE_PATHS on spaces.<br /> IFS="<br /> "</p> <p>for FILE in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> do<br />     if [ ! -e "$DESKTOP/`basename $FILE`" ]<br />     then<br />         ln -s "$FILE" $DESKTOP<br />     fi<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/mount_loopback ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/mount_loopback<br /> <code><br /> #!/bin/sh<br /> # Name: (Un)Mount Loopback<br /> # Description: Allows for mounting and unmounting of loopback filesystems<br /> # Author: Caleb Shay <caleb@webninja.com><br /> # License: GPL<br /> # This script makes several assumptions:<br /> # 1.  You have gdialog installed in your path<br /> # 2.  You have xsu installed in your path<br /> # 3.  You have loopback device support in your kernel<br /> # 4.  You have the mountpints /mnt/loop0 - /mnt/loop7<br /> # 5.  You have your kernel compiled with the default number (8) of loopback devices<br /> # 6.  Your loopback files will either be iso9660 cdroms or efs filesystems<br /> #     (but adding more filesystems is trivial)<br /> for arg<br /> do<br />     skipFile=0;<br />     ftype=$(file "${arg}");<br />     if [ "`df | grep \"${arg}\"`" ]; then<br />         xsu -u root -t "Unmount Loopback Filesystem" -d -e -- umount \"${arg}\";<br />         continue;<br />     fi;<br />     case "$ftype" in<br />         *ISO\ 9660\ CD-ROM\ filesystem*)<br />             mtype="iso9660";<br />         ;;<br />         *SGI\ disk\ label*)<br />             mtype="efs";<br />         ;;<br />         *)<br />             gdialog --msgbox "Don't know how to mount\n${ftype}" 300 400;<br />             skipFile=1;<br />         ;;<br />     esac;<br />     if [ ${skipFile} -lt 1 ]; then<br />         mounted=0;<br />         for loop in loop0 loop1 loop2 loop3 loop4 loop5 loop6 loop7; do<br />             if [ "`df | grep /mnt/${loop}`" ]; then<br />                 echo "Something already mounted on ${loop}";<br />             else<br />                 mounted=1;<br />                 xsu -u root -t "Mount Loopback Filesystem" -d -e -- mount -o loop -t ${mtype} \"${arg}\" /mnt/${loop};<br />                 nautilus /mnt/${loop}<br />                 break;<br />             fi;<br />         done;<br />         if [ ${mounted} -lt 1 ]; then<br />             gdialog --msgbox "No available mount points for ${arg}" 300 200;<br />         fi<br />     fi;<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/moveup ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/moveup<br /> <code><br /> #!/bin/sh<br /> # moveup: moves the selected file(s) to parent directory<br /> # (if able)<br /> for arg<br /> do<br /> if [ -f ../"$arg" ]<br /> then<br /> MSG="Filename: '$arg' already exists in parent directory."<br /> if<br /> gdialog --title "Overwrite?" --defaultno --yesno "$MSG" 200 100<br /> then<br /> mv "$arg" ../"$arg"<br /> fi<br /> else<br /> mv "$arg" ../"$arg"<br /> fi<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/QuickBurn ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/QuickBurn<br /> <code><br /> #!/usr/bin/env python2<br /> # Nautilus CD burning script<br /> #<br /> # Owner: Michele Campeotto <micampe@micampe.it><br /> # http://www.micampe.it<br /> #<br /> # Licence: GNU GPL<br /> # Copyright (C) 2002 Michele Campeotto<br /> #<br /> # Dependency: GTK+ >= 2.0<br /> # PyGTK >= 1.99.8<br /> # Python >= 2.2<br /> # mkisofs and cdrecord<br /> #<br /> # 20020330 - Ver 0.1<br /> # First release</p> <p>import sys, os, os.path, popen2</p> <p>import gtk</p> <p># To configure the script, you should only need to edit these values<br /> device = '0,0,0'<br /> driver = 'mmc_cdr'<br /> options = 'driveropts=burnproof'<br /> dummy = '-dummy'</p> <p># To actually burn CDs, uncomment the following line and comment out the next one<br /> #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 -'<br /> burn_command_template = 'mkisofs -gui -r -J -l -D -L -o image.img -graft-points %(graft_points)s'</p> <p>size_command_template = 'mkisofs -r -J -l -D -L -v -print-size -graft-points %(graft_points)s'</p> <p>def build_mappings(paths):<br /> mappings = []<br /> for i in paths:<br /> if os.path.isdir(i):<br /> mappings.append('"%s/=%s"' % (i.split('/')[-1], i))<br /> else:<br /> mappings.append('"%s=%s"' % (i.split('/')[-1], i))<br /> return mappings</p> <p>def burn_command(paths):<br /> global graft_points<br /> graft_points = ' '.join(build_mappings(paths))<br /> return burn_command_template % globals()</p> <p>def size_command(paths):<br /> global graft_points<br /> graft_points = ' '.join(build_mappings(paths))<br /> return size_command_template % globals()</p> <p>def get_image_size(paths):<br /> return int(os.popen4(size_command(paths))[1].readlines()[-1])</p> <p>def burn(paths, progress):<br /> def cb(fd, cond):<br /> data = os.read(fd, 80)<br /> print data,<br /> if data.find('extents') >= 0:<br /> progress.set_fraction(1.0)<br /> progress.set_text('100%')<br /> return gtk.TRUE<br /> elif data.find('read/written') >= 0:<br /> progress.set_text('Finishing...')<br /> try:<br /> perc = int(data.split('.')[0])<br /> progress.set_fraction(perc/100.0)<br /> progress.set_text('%d%%' % (perc,))<br /> except (ValueError):<br /> pass<br /> command = burn_command(paths)<br /> print command<br /> pipe = popen2.Popen4(command)<br /> gtk.input_add(pipe.fromchild, gtk.gdk.INPUT_READ, cb)<br /> 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("<b>Burning...</b>")<br /> label.set_use_markup(gtk.TRUE)<br /> label.set_alignment(0, 0.5)<br /> vbox.pack_start(label)</p> <p> label = gtk.Label('\n'.join(paths))<br /> label.set_alignment(0, 0.5)<br /> vbox.pack_start(label)</p> <p> win.progress = gtk.ProgressBar()<br /> win.progress.set_fraction(0.0)<br /> win.progress.set_text("Initializing...")<br /> vbox.pack_start(win.progress)</p> <p> win.show_all()<br /> return win</p> <p>def help():<br /> win = gtk.Dialog("Nautilus Quick Burner", None,<br /> gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,<br /> (gtk.STOCK_OK, gtk.RESPONSE_OK))</p> <p> hbox = gtk.HBox(gtk.FALSE, 8)<br /> hbox.set_border_width(8)<br /> win.vbox.pack_start(hbox)</p> <p> stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR,<br /> gtk.ICON_SIZE_DIALOG)<br /> hbox.pack_start(stock)</p> <p> label = gtk.Label("You must specify the files to be burned.")<br /> hbox.pack_start(label)</p> <p> win.show_all()<br /> return win</p> <p>def confirm(paths):<br /> win = gtk.Dialog("Nautilus Quick Burner", None,<br /> gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,<br /> (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,<br /> "_Burn 'em!", gtk.RESPONSE_OK))</p> <p> hbox = gtk.HBox(gtk.FALSE, 8)<br /> hbox.set_border_width(8)<br /> win.vbox.pack_start(hbox)</p> <p> stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION,<br /> gtk.ICON_SIZE_DIALOG)<br /> hbox.pack_start(stock)</p> <p> vbox = gtk.VBox()<br /> vbox.set_spacing(8)<br /> hbox.pack_start(vbox)</p> <p> label = gtk.Label("<b>Are you sure you want to burn these?</b>")<br /> label.set_use_markup(gtk.TRUE)<br /> label.set_alignment(0, 0.5)<br /> vbox.pack_start(label)</p> <p> label = gtk.Label('\n'.join(paths))<br /> label.set_alignment(0, 0.5)<br /> vbox.pack_start(label)</p> <p> win.show_all()<br /> response = win.run()<br /> win.destroy()<br /> return response</p> <p>def error(paths):<br /> win = gtk.Dialog("Burning finished", None,<br /> gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,<br /> (gtk.STOCK_OK, gtk.RESPONSE_OK))</p> <p> hbox = gtk.HBox(gtk.FALSE, 8)<br /> hbox.set_border_width(8)<br /> win.vbox.pack_start(hbox)</p> <p> stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR,<br /> gtk.ICON_SIZE_DIALOG)<br /> hbox.pack_start(stock)</p> <p> vbox = gtk.VBox()<br /> vbox.set_spacing(8)<br /> hbox.pack_start(vbox)</p> <p> label = gtk.Label("<b>Some error occurred while building the image.</b>")<br /> label.set_use_markup(gtk.TRUE)<br /> label.set_alignment(0.0, 0.5)<br /> vbox.pack_start(label)</p> <p> label = gtk.Label("Run:\n<tt>%s</tt>\nfrom the commman line to see what went wrong."<br /> % size_command(paths))<br /> label.set_use_markup(gtk.TRUE)<br /> label.set_selectable(gtk.TRUE)<br /> label.set_line_wrap(gtk.TRUE)<br /> vbox.pack_start(label)</p> <p> win.show_all()<br /> response = win.run()<br /> win.destroy()<br /> return response</p> <p>def success():<br /> win = gtk.Dialog("Burning finished", None,<br /> gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,<br /> (gtk.STOCK_OK, gtk.RESPONSE_OK))</p> <p> hbox = gtk.HBox(gtk.FALSE, 8)<br /> hbox.set_border_width(8)<br /> win.vbox.pack_start(hbox)</p> <p> stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_INFO,<br /> gtk.ICON_SIZE_DIALOG)<br /> hbox.pack_start(stock)</p> <p> label = gtk.Label("Burning process successfully completed.")<br /> hbox.pack_start(label)</p> <p> win.show_all()<br /> response = win.run()<br /> win.destroy()<br /> return response</p> <p>def failed():<br /> win = gtk.Dialog("Burning failed", None,<br /> gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,<br /> (gtk.STOCK_OK, gtk.RESPONSE_OK))</p> <p> hbox = gtk.HBox(gtk.FALSE, 8)<br /> hbox.set_border_width(8)<br /> win.vbox.pack_start(hbox)</p> <p> stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_WARNING,<br /> gtk.ICON_SIZE_DIALOG)<br /> hbox.pack_start(stock)</p> <p> label = gtk.Label("Burning process failed.")<br /> hbox.pack_start(label)</p> <p> win.show_all()<br /> response = win.run()<br /> win.destroy()<br /> return response</p> <p>def main():<br /> global size<br /> if len(sys.argv) == 1:<br /> help().run()<br /> else:<br /> paths = [os.path.abspath(i) for i in sys.argv[1:]]<br /> if confirm(paths) == gtk.RESPONSE_OK:<br /> try:<br /> size = get_image_size(paths)<br /> except ValueError:<br /> error(paths)<br /> else:<br /> win = burn_window(paths)<br /> result = burn(paths, win.progress)<br /> print result<br /> win.destroy()<br /> if result == 0:<br /> success()<br /> else:<br /> failed()</p> <p>if __name__ == '__main__':<br /> main()<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/Search_Here ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/Search_Here<br /> <code><br /> #!/bin/sh<br /> # From Johnathan Bailes<br /> # This script opens a gnome-search-tool in the directory you select.<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Install in your ~/Nautilus/scripts directory.<br /> # You need to be running Nautilus 1.0.3+ to use scripts.</p> <p>cd $NAUTILUS_SCRIPT_CURRENT_URI<br /> exec gnome-search-tool<br /> </code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/set_exec ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/set_exec<br /> <code><br /> #!/bin/sh<br /> # set_exec<br /> # Sets selected files as executable<br /> # looping required for multiple filenames with spaces<br /> for arg<br /> do<br /> chmod u+x "$arg"<br /> done</code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/set_read_only ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/set_read_only<br /> <code><br /> #!/bin/sh<br /> # set_read_only<br /> # Sets selected files as executable<br /> # looping required for multiple filenames with spaces<br /> for arg<br /> do<br /> chmod ugo-w "$arg"<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/shredder ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/shredder<br /> <code></p> <p>#!/bin/bash<br /> # "Shredder" secure file delete for Nautilus<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> # Copyright (C) James Jones <jcjones@ufl.edu><br /> #<br /> # Dependency : gdialog (gnome-utils)<br /> # \A0 : shred (Colin Plumb's)<br /> #<br /> # From shred's info file, wise words:<br /> #<br /> # Please note* that `shred' relies on a very important assumption:<br /> # that the filesystem overwrites data in place.  This is the traditional<br /> # way to do things, but many modern filesystem designs do not satisfy<br /> # this assumption.<br /> #<br /> # Exceptions exist, and are noted in shred's info manual.<br /> # Type 'info shred' from a prompt to see the list. </p> <p>SHRED_PATH=/usr/bin #Path to shred binary.</p> <p>if dialog=`gdialog --title "$1" --yesno "Are you sure you want to shred<br /> $1" 100 200 --defaultno`<br /> then<br />   $SHRED_PATH/shred -zu "$1"<br /> fi</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/UnExec ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/UnExec<br /> <code><br /> #!/bin/sh<br /> #<br /> # This script removes executable bit from all files (excluding directories!)<br /> # recursively. Very useful when you copy files from MS Win partition or from a<br /> # CD recorded on Windows.<br /> #<br /> # Author: Krzysztof Luks <m00se@iq.pl><br /> #<br /> # Copyright (C) 2002 Krzysztof Luks<br /> # Licence: GNU GPL 2 or later.<br /> #</p> <p># set desired mode here<br /> MODE="644"</p> <p># We don't want to split NAUTILUS_SCRIPT_SELECTED_FILE_PATHS on spaces.<br /> IFS="<br /> "</p> <p>for ARG in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> do<br /> if [ -d "$ARG" ]<br /> then<br /> for FILE in `find "$ARG" -type f`<br /> do<br /> chmod -f $MODE "$FILE"<br /> done<br /> elif [ -f "$ARG" ]<br /> then<br /> chmod -f $MODE "$ARG"<br /> fi<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/FileSystemManagement/uppercase ====</h3> <p>$ cat nautilus-scripts/Varios/FileSystemManagement/uppercase<br /> <code><br /> #!/bin/sh<br /> # uppercase: Renames input file to uppercase.<br /> for arg<br /> do<br /> tmp=`echo "$arg" | tr '[a-z]' '[A-Z]'`</p> <p> if [ -f $tmp ]<br /> then<br /> msg="Uppercase filename: '$tmp' already exists."<br /> gdialog --msgbox "$msg" 100 100<br /> else<br /> mv "$arg" "$tmp"<br /> fi<br /> done</code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/convert_to_jpeg ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/convert_to_jpeg<br /> <code><br /> #!/bin/bash</p> <p>while [ $# -gt 0 ]; do<br /> picture=$1<br /> jpg_file=`echo "$picture" | sed 's/\.\w*$/.jpg/'`<br /> /usr/bin/convert -quality 75 "$picture" jpeg:"$jpg_file"<br /> shift<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/convert_to_png ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/convert_to_png<br /> <code><br /> #!/bin/bash</p> <p>while [ $# -gt 0 ]; do<br /> picture=$1<br /> png_file=`echo "$picture" | sed 's/\.\w*$/.png/'`<br /> /usr/bin/convert "$picture" png:"$png_file"<br /> shift<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/Create_Thumbnail ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/Create_Thumbnail<br /> <code><br /> #!/bin/bash<br /> #<br /> # Nautilus script -> Create big Thumbnails (upto 200x200) for selected files<br /> #<br /> # Owner : Hans-Bernhard Tr\FCtken<br /> # hb.truetken@htp-tel.de<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Ver :1.0 Date 06.03.2002<br /> #<br /> # angelehnt an: http://www-user.tu-chemnitz.de/~kbo/linux/shellskript/conv.htm<br /> #<br /> # Dependency : ImageMagick, GNU shell utilities</p> <p>for Datei in $*<br /> do<br /> if [ -f $Datei ]<br /> then<br /> echo "Bearbeite Datei $Datei ..."<br /> DateiName=`basename $Datei`<br /> DirName=`dirname $Datei`/.thumbnails<br /> convert -geometry 200x200 $Datei $DirName/$DateiName.png<br /> fi<br /> done</p> <p>exit 0<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/create-vcd ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/create-vcd<br /> <code><br /> #!/bin/sh<br /> #<br /> # You can select multiple mpegs in Nautilus and and create a VCD CD image in bin/cue format.<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Copyright (C) Keith Conger <acid@twcny.rr.com><br /> #<br /> # This script is for use with Nautilus 1.0.3 + and GNU VCDImager 0.7.x +.</p> <p>VCDIMGR_PATH=/usr/local/bin #Path to vcdimager binary</p> <p>LABEL=$(gdialog --title "VCD Volume Label?" --inputbox "Volume Label.." 200 450 VCD 2>&1)<br /> DIR=$(gdialog --title "VCD Image Directory?" --inputbox "Directory Location..." 200 450 ~/tmp/$1 2>&1)</p> <p>mkdir $DIR</p> <p>vcdimager --iso-volume-label=$LABEL --bin-file=$DIR/$1.bin --cue-file=$DIR/$1.cue $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS >> $DIR/$1.log</p> <p>gdialog --separate-output --title "VCD Imager log" --textbox $DIR/$1.log 50 70 2>&1<br /> rm $DIR/$1.log</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/dv_to_mpg ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/dv_to_mpg<br /> <code><br /> #!/bin/bash<br /> #<br /> # You can select DV type2 stream and convert it into a vcd compliant<br /> # mpeg.<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Copyright (C) Keith Conger <acid@twcny.rr.com><br /> #<br /> # This script is for use with Nautilus 1.0.3 + and mjpegtools(CVS).<br /> # Optional: gnome-utils and Xdialog</p> <p># Set this to either Xdialog, gdialog or none.<br /> DIALOG=Xdialog</p> <p>#Directory for temporary files<br /> TMP_DIR=~/tmp</p> <p>if [ "$DIALOG" = "Xdialog" ]; then<br /> OUT_FILE=$(Xdialog --fselect ~/tmp 0 0 2>&1)<br /> (<br /> echo "0";<br /> lav2wav $1 |mp2enc -V -o $TMP_DIR/sound.mpg<br /> echo "35";<br /> lav2yuv $1|yuvscaler -O VCD|mpeg2enc -f 1 -r 16 -o $TMP_DIR/video.mpg<br /> echo "90";<br /> mplex -f 1 $TMP_DIR/sound.mpg $TMP_DIR/video.mpg -o $OUT_FILE<br /> echo "100";<br /> rm $TMP_DIR/sound.mpg $TMP_DIR/video.mpg<br /> )|<br /> Xdialog --title "Creating MPEG.." --gauge "Percent complete:" 8 30<br /> elif [ "$DIALOG" = "gdialog" ]; then<br /> DIR=$(gdialog --title "MPEG file directory" --inputbox "Directory Location..." 200 450 ~/tmp/$1 2>&1)<br /> lav2wav $1 |mp2enc -V -o $TMP_DIR/sound.mpg<br /> lav2yuv $1|yuvscaler -O VCD|mpeg2enc -f 1 -r 16 -o $TMP_DIR/video.mpg<br /> mplex -f 1 $TMP_DIR/sound.mpg $TMP_DIR/video.mpg -o $DIR/$1.mpg<br /> rm $TMP_DIR/sound.mpg $TMP_DIR/video.mpg<br /> else<br /> lav2wav $1 |mp2enc -V -o $TMP_DIR/sound.mpg<br /> lav2yuv $1|yuvscaler -O VCD|mpeg2enc -f 1 -r 16 -o $TMP_DIR/video.mpg<br /> mplex -f 1 $TMP_DIR/sound.mpg $TMP_DIR/video.mpg -o ./$1.mpg<br /> rm $TMP_DIR/sound.mpg $TMP_DIR/video.mpg<br /> fi</code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/mirror_jpg ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/mirror_jpg<br /> <code><br /> #!/usr/bin/perl -w</p> <p># created on Sept. 14 by Shane Mueller<br /> # http://g-scripts.sourceforge.net<br /> # Based on script of:<br /> # Matt Doller <mdoller@wpi.edu><br /> #<br /> # some code is borrowed from a script i found on tigert's web site<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU Library General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> <p>use Gtk;<br /> use strict;</p> <p>set_locale Gtk;<br /> init Gtk;</p> <p>my $false = 0;<br /> my $true = 1;</p> <p>my $window;<br /> my $box1;<br /> my $box2;<br /> my $label;<br /> my $pbar;<br /> my $button;<br /> my $separator;<br /> my $file;<br /> my $filenum;<br /> my $random_file;</p> <p># Create the window<br /> $window = new Gtk::Window( "toplevel" );<br /> $window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );<br /> $window->set_title( "Rotating JPEG Images..." );<br /> $window->border_width( 0 );</p> <p>$box1 = new Gtk::VBox( $false, 0 );<br /> $box1->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $false, 0 );<br /> $box2->show();<br /> $window->add( $box1 );</p> <p># Create the label at the top of the window<br /> $label = new Gtk::Label( "Rotating JPEG Images...\n" );<br /> $box2->pack_start( $label, $false, $false, 0);<br /> $label->show();</p> <p># Create the progress bar<br /> $pbar = new Gtk::ProgressBar();<br /> $box2->pack_start( $pbar, $true, $true, 0);<br /> $pbar->show();</p> <p>$separator = new Gtk::HSeparator();<br /> $box1->pack_start( $separator, $false, $false, 0 );<br /> $separator->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $true, 0 );<br /> $box2->show();</p> <p># Create the close button<br /> $button = new Gtk::Button( "Cancel" );<br /> $button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );</p> <p>$box2->pack_start( $button, $true, $true, 0 );<br /> $button->can_default( $true );<br /> $button->grab_default();<br /> $button->show();</p> <p>$window->show();</p> <p>Gtk->main_iteration while ( Gtk->events_pending );</p> <p># set up loop to go through files passed to script<br /> # rotate each script, increment the file number, and then update the status<br /> # for now, assume that they are all jpegs, and do not put up a warning</p> <p>$filenum = 0;</p> <p>$random_file = "/tmp/rotate-image-" . time;</p> <p>foreach $file (@ARGV) {<br /> ++$filenum;<br /> $label->set_text( "Rotating JPEG Image:\n$file" );<br /> $pbar->set_value( ( 100 * $filenum ) / ( $#ARGV + 1 ) );</p> <p> print( "\"$file\"\n$random_file\n" );<br /> system( "jpegtran -copy all -flip horizontal \"$file\" 2>&1 > $random_file" );<br /> if ( $? == 0 )<br /> {<br /> system( "mv -f $random_file \"$file\"" );<br /> }<br /> else<br /> {<br /> # an error occurred in the jpegtran... for now, just leave it alone. we can analyze the error, and put up a dialog<br /> # as soon as i figure out how to do that with gtk-perl (well)<br /> } </p> <p> system( "rm -f $random_file" );</p> <p> Gtk->main_iteration while ( Gtk->events_pending );<br /> }</p> <p>$button->child->set( "Done" );</p> <p>main Gtk;<br /> exit( 0 );<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/Naudilus ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/Naudilus<br /> <code><br /> #!/bin/bash</p> <p># Naudilus - Nautilus script for audio file conversion<br /> # by Rafael Rigues <<EMAIL: PROTECTED>> - 02/28/2002<br /> # Translations and feedback are welcome!</p> <p># Depends on lame (3.91 recommended), gidalog and vorbis tools and libraries (rc 3 or newer)<br /> # Based on code from convert_to_jpeg (David Westlund)<br /> # Based on code from Archiver/Unarchiver (Patrick Largey & David Westlund)<br /> # Thanks to Aur\E9lio Marinho Jargas for miscellaneous help</p> <p># Put on ~/.gnome/nautilus-scripts, and chmod +x it!</p> <p># Changelog:</p> <p># 03/17/2002 * Version 0.5<br /> # * Info: This version was finished on 03/05/2002, and was meant for personal use only.<br /> # (at least until I had implemented everything I wanted). However, I'm releasing it now<br /> # to get feedback from other users.<br /> # * I've discovered the cause for oggenc always encoding files at 342 kbps. It seems to<br /> # be a bug triggered by the combination of glibc-2.2.4-19.3 and vorbis rc 1. Upgrading<br /> # the vorbis tools and libraries to rc 3 solved the problem.<br /> # * I've also found that not all versions of lame have the --decode option. I don't know<br /> # when it was added to lame (and I'm too lazy to check the changelog now), but I'm<br /> # using lame 3.91.<br /> # * Now I'm using pipes to decode/encode the file simultaneously (thanks to FRS for being<br /> # so persistent about this), so there's no need to create (and delete, afterwards) a<br /> # temporary WAV file. It's also one less thing to check if it will be overwritten or not.<br /> # * More code cleanups. "...Smarter! Stronger! More Aggressive! I feellike I could..." :)<br /> # * Now also converts WAVE files to MP3 or Vorbis!</p> <p># 03/03/2002 * Version 0.4</p> <p># * Spent a whole day trying to reorganize the code, tighten it up and make it look<br /> # smarter and prettier. Did I succeed? :)<br /> # * Now Naudilus detects if the file exists (both the temporary .wav file created during<br /> # the conversion and the resulting .mp3 or .ogg file) and asks the user if he wants the<br /> # the file to be overwritten. If not, the file is ignored, and Naudilus will proceed<br /> # with the next file.<br /> # * I've found a strange bug where oggenc is now ALWAYS encoding the files at an average<br /> # 342 Kbps, regardless of the arguments I pass to it. I suspect it is a fault on the ogg<br /> # encoder, caused by a full-scale system update (which included a new version of glibc) I<br /> # did today. I will find out more about this tomorrow, when I test the script on my<br /> # machine at work.</p> <p># 03/02/2002 * Version 0.3</p> <p># * Naudilus now asks which format to convert the files to. Note that if you choose<br /> # to convert a file to it's current format (eg. convert an MP3 file to MP3), it<br /> # will be simply ignored, and Naudilus will proceed with the next file.<br /> # * Possible conversions are: MP3 -> WAV, Ogg -> WAV, MP3 -> Ogg and Ogg -> MP3.</p> <p># 03/01/2002 * Version 0.2</p> <p># * Changed the name to "Naudilus". Thanks to Fabio Ricardo Schmidlin for the name!<br /> # * Detects the filetype before attempting to convert the file.<br /> # * Uses the file extension to determine which kind of file it is, if the filetype<br /> # detection fails.<br /> # * Added Vorbis to MP3 conversion.</p> <p># 02/28/2002 * First version. It seems to work! :) </p> <p># And now, the incredible, ever expanding TO-DO list!!</p> <p># * Check for write permission before trying to create a file. If such permission does not exist, ask<br /> # the user where to write the file.<br /> # * Recurse directories and subdirectories (Dangerous??)<br /> # * Generate MP3/Ogg files with complete tags (artist, album, genre, etc...). Grab the tags from the<br /> # original MP3/Ogg file </p> <p># Talk is cheap! Now show me the code!!!</p> <p># Version number</p> <p>version="0.5"</p> <p># Messages<br /> # English, by Myself<br /> wait="Naudilus "$version" - Please Wait..."<br /> warning="Naudilus "$version" - WARNING!"<br /> converting="Converting your audio files. Get some coffee and come back later"<br /> which_format="Convert files to which format?"<br /> format_mp3="Mpeg Layer III (MP3)"<br /> format_ogg="Ogg Vorbis"<br /> format_wav="Microsoft WAV"<br /> overwrite="The file: "<br /> proceed=" will be overwritten. Proceed?"</p> <p>case $LANG in</p> <p> pt* )<br /> # Brazilian Portuguese, also by Myself<br /> wait="Naudilus "$version" - Aguarde..."<br /> warning="Naudilus "$version" - AVISO!"<br /> converting="Convertendo seus arquivos de \E1udio. Pegue um caf\E9 e volte mais tarde"<br /> which_format="Converter arquivos para qual formato?"<br /> format_mp3="Mpeg Layer III (MP3)"<br /> format_ogg="Ogg Vorbis"<br /> format_wav="Microsoft WAV"<br /> overwrite="O arquivo: "<br /> proceed=" ser\E1 sobrescrito. Devo continuar?";;</p> <p> fr* )<br /> wait=3D"Naudilus "$version" - Veuillez patienter..."<br /> warning=3D"Naudilus "$version" - ATTENTION!"<br /> converting=3D"La conversion de vos fichiers audio est en cours, veuillez prendre un caf=E9 et revenir plus tard"<br /> which_format=3D"Dans quel format voulez-vous convertir le(s) fichier(s)?"<br /> format_mp3=3D"Mpeg Layer III (MP3)"<br /> format_ogg=3D"Ogg Vorbis"<br /> format_wav=3D"Microsoft WAV"<br /> overwrite=3D"Le fichier : "<br /> proceed=3D" sera =E9cras=E9, voulez-vous poursuivre?";;</p> <p> eo* )<br /> wait="Naudilus "$version" - Bonvolu atendi..."<br /> warning="Naudilus "$version" - AVERTU!"<br /> converting="Konvertas viajn aŭdiajn dosierojn. Trinku iom da kafo kaj revenu poste."<br /> which_format="Konvertu dosierojn al kiu formato?"<br /> format_mp3="Mpeg Layer III (MP3)"<br /> format_ogg="Ogg Vorbis"<br /> format_wav="Microsoft WAV"<br /> overwrite="La dosiero: "<br /> proceed=" estas superskribota. \C4?u procedu?";;</p> <p> sv*)<br /> wait="Naudilus "$version" - Var god v\E4nta..."<br /> warning="Naudilus "$version" - Varning!"<br /> converting="Konverterar dina ljudfiler. H\E4mta lite kaffe och kom tillbaks senare"<br /> which_format="Vilket format ska filerna konverteras till?"<br /> format_mp3="Mpeg Lager III (MP3)"<br /> format_ogg="Ogg Vorbis"<br /> format_wav="Microsoft WAV"<br /> overwrite="Filen: "<br /> proceed=" Kommer skrivas \F6ver. Vill du forts\E4tta?";;</p> <p>esac</p> <p># Select file format to convert file to</p> <p>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`</p> <p>if [ "$selected_format" != "" ]<br /> then<br /> # Do Nothing...<br /> echo "$selected_format" > /dev/null<br /> else<br /> exit 0<br /> fi</p> <p># Warn the user that the conversion will take a LONG time...</p> <p>gdialog --title "$wait" --msgbox "$converting" 100 100&</p> <p># Do the conversion</p> <p>while [ $# -gt 0 ]; do</p> <p> in_file=$1<br /> out_file=`echo "$in_file" | sed 's/\.\w*$/'$selected_format'/'`</p> <p> while `true`; do</p> <p> # Is the input file different from the output file?</p> <p> if [ "$in_file" = "$out_file" ]<br /> then<br /> # No, break and go to the next file...<br /> break<br /> fi</p> <p> # Does the output file exists? If yes, asks the user if he wants to<br /> # overwrite.</p> <p> if [ "`ls "$out_file" | grep -v "^ls"`" != "" ]<br /> then<br /> if !(`gdialog --title "$warning" --yesno "$overwrite \"$out_file\"$proceed" 200 100`)<br /> then<br /> # Don't owerwrite, so we get out of here.<br /> break<br /> fi<br /> fi</p> <p> # Lets see... Is it an MP3 file?<br /> # Some MP3 files created with Apple's iTunes or some Windows encoders<br /> # do not report the correct filetype when the 'file' command is used<br /> # (it says "data", instead of "MP3, xxx kBits, xx.x kHz, Stereo...").<br /> # So, we need to also check the file extension, and hope it's a real<br /> # MP3 file...</p> <p> if [ "`file -b "$1" | grep 'MP3'`" != "" ] || [ "`echo $in_file | grep -i '\.mp3$'`" != "" ]<br /> then<br /> if [ "$selected_format" = ".ogg" ]<br /> then<br /> lame --quiet --decode "$in_file" - | oggenc - -Q -b 128 -M 160 -o "$out_file"<br /> else<br /> lame --quiet --decode "$in_file" "$out_file"<br /> fi<br /> break<br /> fi</p> <p> # Hmmm... Does not have an MP3 signature, nor .mp3 extension. Maybe<br /> # an Ogg-Vorbis file? Just to be sure, we also check the file extension</p> <p> if [ "`file -b "$1" | grep 'Vorbis'`" != "" ] || [ "`echo $in_file | grep -i '\.ogg$'`" != "" ]<br /> then<br /> if [ "$selected_format" = ".mp3" ]<br /> then<br /> ogg123 -q --device=wav "$in_file" -f - | lame --quiet -m auto -v -F -b 128 -B 160 -h - "$out_file"<br /> else<br /> ogg123 -q --device=wav "$in_file" -f "$out_file"<br /> fi<br /> break<br /> fi</p> <p> # The last resort is to see if it is a .WAV file.. Also checking<br /> # the file extension, of course!</p> <p> if [ "`file -b "$1" | grep 'WAVE'`" != "" ] || [ "`echo $in_file | grep -i '\.wav$'`" != "" ]<br /> then<br /> if [ "$selected_format" = ".mp3" ]<br /> then<br /> lame --quiet -m auto -h -v -F -b 128 -B 160 "$in_file" "$out_file"<br /> else<br /> oggenc "$in_file" -Q -b 128 -M 160 -o "$out_file"<br /> fi<br /> break<br /> fi </p> <p> break<br /> shift<br /> done</p> <p>shift<br /> done </p> <p># Kill the warning</p> <p>kill `ps -ef | grep "gdialog --title" | gawk '{ print $8, $2}' | grep gdialog | gawk '{ print $2 }'` 2> /dev/null</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/Play_in_XMMS ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/Play_in_XMMS<br /> <code><br /> #!/usr/bin/python<br /> #<br /> # simple script to recurse a subtree, find all the mp3 and queue them to<br /> # XMMS.<br /> #<br /> # Please modify this script! My python is rusty at best.<br /> #<br /> # Travis Hume -- travis@usermail.com<br /> # Thu Oct 24 11:06:54 2002<br /> #<br /> # Barak Korren - ifireball@yahoo.com<br /> # Sat Apr 03 2004<br /> # Some bugfixes, now preserves alphanumerical file-ordering in<br /> # sub-directories</p> <p>import sys, glob, os, os.path, dircache</p> <p>def isAudioFile( f ):<br /> # to support additional file types just add their appropriate<br /> # extentions to this list (lower case).<br /> file_types = ['.mp3','.ogg','.wav']</p> <p> p,ext = os.path.splitext(f)<br /> try:<br /> file_types.index(ext.lower())<br /> except:<br /> return False</p> <p> return True</p> <p># change this to something other than None to make the script<br /> # follow symlinks<br /> follow_links = None</p> <p>def find_mp3s( dirs=None ):<br /> """ finds all mp3 files rooted at dirs and returns them as a list """<br /> if not dirs:<br /> return []</p> <p> mp3s = []<br /> while dirs:<br /> if os.path.isfile(dirs[0]) and isAudioFile(dirs[0]):<br /> mp3s.append(dirs[0])<br /> dirs = dirs[1:]<br /> elif os.path.isdir(dirs[0]):<br /> found_dirs = []<br /> for f in dircache.listdir( dirs[0] ):<br /> p = dirs[0] + "/" + f;<br /> if os.path.isfile(p) and isAudioFile(p):<br /> mp3s.append( p )<br /> elif os.path.isdir( p ) and not f.endswith( "/proc" ):<br /> if not os.path.islink( p ) or follow_links:<br /> found_dirs.append( p )</p> <p> dirs = found_dirs + dirs[1:]</p> <p> return mp3s</p> <p>dirs = sys.argv[1:]<br /> dirs.reverse()<br /> mp3s = find_mp3s( dirs )<br /> #inf = "";<br /> #for mp3 in mp3s:<br /> # inf = inf + '"' + mp3 + '"' + "\n"<br /> #os.execvp("zenity", ['zenity','--info','--text=' + inf] )<br /> os.execvp("xmms", ['xmms','-p'] + mp3s )<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/queue_to_xmms ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/queue_to_xmms<br /> <code><br /> #!/usr/bin/python<br /> #<br /> # simple script to recurse a subtree, find all the mp3 and queue them to<br /> # XMMS.<br /> #<br /> # Please modify this script! My python is rusty at best.<br /> #<br /> # Travis Hume -- travis@usermail.com<br /> # Thu Oct 24 11:06:54 2002</p> <p>import sys, glob, os, os.path</p> <p>FALSE,TRUE = 0,1</p> <p>def isAudioFile( f ):<br /> # to support additional file types just add their appropriate<br /> # extentions to this list (lower case).<br /> file_types = ['.mp3','.ogg','.wav']</p> <p> p,ext = os.path.splitext(f)<br /> try:<br /> file_types.index(ext.lower())<br /> except:<br /> return FALSE</p> <p> return TRUE</p> <p># change this to something other than None to make the script<br /> # follow symlinks<br /> follow_links = None</p> <p>def find_mp3s( dirs=None ):<br /> """ finds all mp3 files rooted at dirs and returns them as a list """<br /> if not dirs:<br /> return []</p> <p> mp3s = []<br /> while dirs:<br /> if os.path.isfile(dirs[0]) and isAudioFile(dirs[0]):<br /> mp3s.append(dirs[0])<br /> else:<br /> found_dirs = []<br /> for f in glob.glob( dirs[0] + "/*" ):<br /> if os.path.isfile(f) and isAudioFile(f):<br /> mp3s.append( f )</p> <p> if os.path.islink( f ):<br /> if follow_links:<br /> found_dirs.append( f )<br /> elif os.path.isdir( f ) and not f.endswith( "/proc" ):<br /> found_dirs.append( f )</p> <p> dirs = found_dirs + dirs[1:]</p> <p> return mp3s</p> <p>dirs = sys.argv[1:]<br /> dirs.reverse()<br /> mp3s = find_mp3s( dirs )<br /> os.execvp("xmms", ['xmms','-p']+mp3s )<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/Queue_to_XMMS ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/Queue_to_XMMS<br /> <code><br /> #!/usr/bin/perl -Wall<br /> #<br /> my @mp3s = reverse (@ARGV);</p> <p>foreach (@mp3s) {<br /> system ("xmms -e \"$_\"");<br /> }<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/rotate ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/rotate<br /> <code><br /> #!/usr/bin/perl -w</p> <p># created on Mon Jul 16 17:21:44 EDT 2001<br /> # Matt Doller <mdoller@wpi.edu><br /> # Alex Bennee <alex@bennee.com> (some additional hacks)<br /> #<br /> # some code is borrowed from a script i found on tigert's web site<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU Library General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> <p>### Instructions for Use:<br /> # 1. If used on a remote file system (e.g. NFS mount) you need to parse<br /> # the NAUTILUS_URI environment variables to get your files.<br /> #<br /> # 2. Having two scripts do the same thing is wasteful (and cut and and<br /> # paste error prone) so this script decides what its going to do based on<br /> # the name of the script (so you symlink "rotate right" and "rotate left"<br /> # to the same file).<br /> #<br /> # 3. Now need for a system call to remove files. unlink will work<br /> #</p> <p>use Gtk;<br /> use strict;</p> <p>(my $me = $0) =~ s|.*/(.*)|$1|;</p> <p>set_locale Gtk;<br /> init Gtk;</p> <p>my $false = 0;<br /> my $true = 1;</p> <p>my $window;<br /> my $box1;<br /> my $box2;<br /> my $label;<br /> my $pbar;<br /> my $button;<br /> my $separator;<br /> my $file;<br /> my $filenum;<br /> my $random_file;</p> <p># Create the window<br /> $window = new Gtk::Window( "toplevel" );<br /> $window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );<br /> $window->set_title( "Rotating JPEG Images..." );<br /> $window->border_width( 0 );</p> <p>$box1 = new Gtk::VBox( $false, 0 );<br /> $box1->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $false, 0 );<br /> $box2->show();<br /> $window->add( $box1 );</p> <p># Create the label at the top of the window<br /> $label = new Gtk::Label( "Rotating JPEG Images...\n" );<br /> $box2->pack_start( $label, $false, $false, 0);<br /> $label->show();</p> <p># Create the progress bar<br /> $pbar = new Gtk::ProgressBar();<br /> $box2->pack_start( $pbar, $true, $true, 0);<br /> $pbar->show();</p> <p>$separator = new Gtk::HSeparator();<br /> $box1->pack_start( $separator, $false, $false, 0 );<br /> $separator->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $true, 0 );<br /> $box2->show();</p> <p># Create the close button<br /> $button = new Gtk::Button( "Cancel" );<br /> $button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );</p> <p>$box2->pack_start( $button, $true, $true, 0 );<br /> $button->can_default( $true );<br /> $button->grab_default();<br /> $button->show();</p> <p>$window->show();</p> <p>Gtk->main_iteration while ( Gtk->events_pending );</p> <p># Decide what command we are executaing based on the calling<br /> # name of the script (so we can symlink version)<br /> my $command = "jpegtran -copy all ";<br /> my $direction;</p> <p>if ( $me =~ /right/ )<br /> {<br /> $command = $command." -rotate 90 ";<br /> $direction = "Right";<br /> } else {<br /> $command = $command." -rotate 270 ";<br /> $direction = "Right";<br /> }</p> <p># set up loop to go through files passed to script<br /> # rotate each script, increment the file number, and then update the status<br /> # for now, assume that they are all jpegs, and do not put up a warning</p> <p>$filenum = 0;</p> <p>$random_file = "/tmp/rotate-image-" . time;<br /> my @filelist;</p> <p># test for argv as Nautilus could just use URI's<br /> if (@ARGV) {<br /> @filelist=@ARGV;<br /> } else {<br /> #extract files from NAUTILUS_SCRIPT_SELECTED_URIS<br /> @filelist = split ("\n", $ENV{NAUTILUS_SCRIPT_SELECTED_URIS} );<br /> }</p> <p>foreach $file (@filelist) {<br /> $file =~ s|^file://||; # drop any file://<br /> ++$filenum;<br /> $label->set_text( "Rotating JPEG Image $direction:\n$file" );<br /> $pbar->set_value( ( 100 * $filenum ) / ( scalar(@filelist) + 1 ) );<br /> system( "$command \"$file\" 2>&1 > $random_file" );<br /> if ( $? == 0 )<br /> {<br /> system( "mv -f $random_file \"$file\"" );<br /> }<br /> else<br /> {<br /> # an error occurred in the jpegtran... for now, just leave it<br /> # alone. we can analyze the error, and put up a dialog<br /> # as soon as i figure out how to do that with gtk-perl (well)<br /> }<br /> print LOG "File:",$file,"\n";<br /> unlink $random_file;<br /> Gtk->main_iteration while ( Gtk->events_pending );<br /> }</p> <p>$pbar->set_value(100);</p> <p>$button->child->set( "Done" );</p> <p>main Gtk;<br /> exit( 0 );<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/rotate_image ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/rotate_image<br /> <code><br /> #!/bin/bash</p> <p># FILE: rotate_image --<br /> # AUTHOR: W. Michael Petullo <mike@flyn.org><br /> # DATE: 31 May 2001<br /> #<br /> # Copyright (C) 2001 W. Michael Petullo <mike@flyn.org><br /> # All rights reserved.<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA</p> <p>mogrify -rotate 90 $*<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/rotate_jpg_left ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/rotate_jpg_left<br /> <code><br /> #!/usr/bin/perl -w</p> <p># created on Mon Jul 16 17:21:44 EDT 2001<br /> # Matt Doller <mdoller@wpi.edu><br /> #<br /> # some code is borrowed from a script I found on Tigert's web site<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU Library General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> <p>use Gtk;<br /> use strict;</p> <p>set_locale Gtk;<br /> init Gtk;</p> <p>my $false = 0;<br /> my $true = 1;</p> <p>my $window;<br /> my $box1;<br /> my $box2;<br /> my $label;<br /> my $pbar;<br /> my $button;<br /> my $separator;<br /> my $file;<br /> my $filenum;<br /> my $random_file;</p> <p># Create the window<br /> $window = new Gtk::Window( "toplevel" );<br /> $window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );<br /> $window->set_title( "Rotating JPEG Images..." );<br /> $window->border_width( 0 );</p> <p>$box1 = new Gtk::VBox( $false, 0 );<br /> $box1->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $false, 0 );<br /> $box2->show();<br /> $window->add( $box1 );</p> <p># Create the label at the top of the window<br /> $label = new Gtk::Label( "Rotating JPEG Images...\n" );<br /> $box2->pack_start( $label, $false, $false, 0);<br /> $label->show();</p> <p># Create the progress bar<br /> $pbar = new Gtk::ProgressBar();<br /> $box2->pack_start( $pbar, $true, $true, 0);<br /> $pbar->show();</p> <p>$separator = new Gtk::HSeparator();<br /> $box1->pack_start( $separator, $false, $false, 0 );<br /> $separator->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $true, 0 );<br /> $box2->show();</p> <p># Create the close button<br /> $button = new Gtk::Button( "Cancel" );<br /> $button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );</p> <p>$box2->pack_start( $button, $true, $true, 0 );<br /> $button->can_default( $true );<br /> $button->grab_default();<br /> $button->show();</p> <p>$window->show();</p> <p>Gtk->main_iteration while ( Gtk->events_pending );</p> <p># set up loop to go through files passed to script<br /> # rotate each script, increment the file number, and then update the status<br /> # for now, assume that they are all jpegs, and do not put up a warning</p> <p>$filenum = 0;</p> <p>$random_file = "/tmp/rotate-image-" . time;</p> <p>foreach $file (@ARGV) {<br /> ++$filenum;<br /> $label->set_text( "Rotating JPEG Image:\n$file" );<br /> $pbar->set_value( ( 100 * $filenum ) / ( $#ARGV + 1 ) );</p> <p> print( "\"$file\"\n$random_file\n" );<br /> system( "jpegtran -copy all -rotate 270 \"$file\" 2>&1 > $random_file" );<br /> if ( $? == 0 )<br /> {<br /> system( "mv -f $random_file \"$file\"" );<br /> }<br /> else<br /> {<br /> # an error occurred in the jpegtran... for now, just leave it alone. we can analyze the error, and put up a dialog<br /> # as soon as i figure out how to do that with gtk-perl<br /> } </p> <p> system( "rm -f $random_file" );</p> <p> Gtk->main_iteration while ( Gtk->events_pending );<br /> }</p> <p>$button->child->set( "Done" );</p> <p>main Gtk;<br /> exit( 0 );<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/rotate_jpg_right ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/rotate_jpg_right<br /> <code><br /> #!/usr/bin/perl -w</p> <p># created on Mon Jul 16 17:21:44 EDT 2001<br /> # Matt Doller <mdoller@wpi.edu><br /> #<br /> # some code is borrowed from a script i found on tigert's web site<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU Library General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.</p> <p>use Gtk;<br /> use strict;</p> <p>set_locale Gtk;<br /> init Gtk;</p> <p>my $false = 0;<br /> my $true = 1;</p> <p>my $window;<br /> my $box1;<br /> my $box2;<br /> my $label;<br /> my $pbar;<br /> my $button;<br /> my $separator;<br /> my $file;<br /> my $filenum;<br /> my $random_file;</p> <p># Create the window<br /> $window = new Gtk::Window( "toplevel" );<br /> $window->signal_connect( "delete_event", sub { Gtk->exit( 0 ); } );<br /> $window->set_title( "Rotating JPEG Images..." );<br /> $window->border_width( 0 );</p> <p>$box1 = new Gtk::VBox( $false, 0 );<br /> $box1->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $false, 0 );<br /> $box2->show();<br /> $window->add( $box1 );</p> <p># Create the label at the top of the window<br /> $label = new Gtk::Label( "Rotating JPEG Images...\n" );<br /> $box2->pack_start( $label, $false, $false, 0);<br /> $label->show();</p> <p># Create the progress bar<br /> $pbar = new Gtk::ProgressBar();<br /> $box2->pack_start( $pbar, $true, $true, 0);<br /> $pbar->show();</p> <p>$separator = new Gtk::HSeparator();<br /> $box1->pack_start( $separator, $false, $false, 0 );<br /> $separator->show();</p> <p>$box2 = new Gtk::VBox( $false, 10 );<br /> $box2->border_width( 10 );<br /> $box1->pack_start( $box2, $false, $true, 0 );<br /> $box2->show();</p> <p># Create the close button<br /> $button = new Gtk::Button( "Cancel" );<br /> $button->signal_connect( "clicked", sub { Gtk->exit( 0 ); } );</p> <p>$box2->pack_start( $button, $true, $true, 0 );<br /> $button->can_default( $true );<br /> $button->grab_default();<br /> $button->show();</p> <p>$window->show();</p> <p>Gtk->main_iteration while ( Gtk->events_pending );</p> <p># set up loop to go through files passed to script<br /> # rotate each script, increment the file number, and then update the status<br /> # for now, assume that they are all jpegs, and do not put up a warning</p> <p>$filenum = 0;</p> <p>$random_file = "/tmp/rotate-image-" . time;</p> <p>foreach $file (@ARGV) {<br /> ++$filenum;<br /> $label->set_text( "Rotating JPEG Image:\n$file" );<br /> $pbar->set_value( ( 100 * $filenum ) / ( $#ARGV + 1 ) );</p> <p> print( "\"$file\"\n$random_file\n" );<br /> system( "jpegtran -copy all -rotate 90 \"$file\" 2>&1 > $random_file" );<br /> if ( $? == 0 )<br /> {<br /> system( "mv -f $random_file \"$file\"" );<br /> }<br /> else<br /> {<br /> # an error occurred in the jpegtran... for now, just leave it alone. we can analyze the error, and put up a dialog<br /> # as soon as i figure out how to do that with gtk-perl (well)<br /> } </p> <p> system( "rm -f $random_file" );</p> <p> Gtk->main_iteration while ( Gtk->events_pending );<br /> }</p> <p>$button->child->set( "Done" );</p> <p>main Gtk;<br /> exit( 0 );<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/scale_image ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/scale_image<br /> <code><br /> #!/bin/bash<br /> title="Scale image"<br /> scale="Size to scale to <length>x<hight>"</p> <p>case $LANG in<br /> sv* )<br /> title="Skala bild"<br /> scale="Storlek att skala till <l\E4ngd>x<h\F6jd>";;<br /> esac</p> <p>imgsize=`gdialog --title "$title" --inputbox "$scale" 200 100 2>&1`</p> <p>while [ $# -gt 0 ]; do<br /> picture=$1<br /> /usr/bin/convert -scale $imgsize "$picture" "$imgsize-$picture"<br /> shift<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/scale_image_to_sizes ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/scale_image_to_sizes<br /> <code><br /> #!/bin/bash<br /> title="Scale image"<br /> scale="Choose which sizes to scale to"<br /> case $LANG in<br /> sv* )<br /> title="Skala bild"<br /> scale="V\E4lj storlekar att skala bilden till";;<br /> esac</p> <p>imgsize=`gdialog --title "$title" --checklist "$scale" 200 100 6 1600x1400 " " off 1280x1024 " " off 1024x768 " " off 800x600 " " off 640x480 " " off 2>&1`</p> <p>while [ $# -gt 0 ]; do<br /> picture=$1<br /> for i in $imgsize; do<br /> i=`echo $i | sed 's/"//g'`<br /> /usr/bin/convert -scale $i "$picture" "$i-$picture"<br /> done</p> <p> shift<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/Show_Digital_Photo_EXIF_data ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/Show_Digital_Photo_EXIF_data<br /> <code><br /> #!/usr/bin/perl -w</p> <p># # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #<br /> # #<br /> # EXIF Dump script for Nautilus #<br /> # #<br /> # Shows various things modern digital cameras embed in the image files #<br /> # like exposure time and aperture and other interesting information. #<br /> # #<br /> # Depends on gdialog for the display part and jhead for the actual #<br /> # EXIF data parsing from the images. You can get jhead from #<br /> # http://www.sentex.net/~mwandel/jhead/, it probably works on anything #<br /> # that has a C compiler. Happy notice is that it does work on linux/ppc #<br /> # as well. #<br /> # #<br /> # Hacked together by Tuomas Kuosmanen <tigert@ximian.com> and #<br /> # Jakub Steiner <jimmac@ximian.com> (icons) #<br /> # Released under the GPL license. #<br /> # #<br /> # The code is ugly, but it worksforme and this is perl. #<br /> # My perl is ugly. -tigert- #<br /> # #<br /> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # </p> <p>use POSIX;<br /> use Digest::MD5 qw(md5_hex);</p> <p>die "No files.. Easy job." unless @ARGV;</p> <p>$hash = md5_hex(localtime);<br /> $tempfile = "/tmp/foo.$hash";</p> <p>foreach $file (@ARGV) {<br /> $reply=`jhead \"$file\" 2>&1 > $tempfile`;<br /> # print("REPLY:: $reply\n");<br /> if ($reply =~ "aborting") {<br /> system("gdialog --title \"EXIF Data Error\" --msgbox \"The file $file does not contain any EXIF information.\" 100 100");<br /> } else {<br /> system("gdialog --title \"EXIF Information for $file\" --textbox $tempfile 34 42");<br /> }<br /> }<br /> system("rm $tempfile");</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/slideshow ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/slideshow<br /> <code><br /> #!/bin/bash</p> <p>###############################################################################<br /> # Display a fullscreen slideshow of the selected files<br /> ###############################################################################<br /> #<br /> # AUTHOR:       Brian Connelly <pub@bconnelly.net> #<br /> # DESCRIPTION:  This script displays a fullscreen slideshow of the files which<br /> #               have been selected in Nautilus.<br /> #<br /> # REQUIREMENTS: Nautilus file manager<br /> #               feh (see http://www.linuxbrit.co.uk)<br /> #               gdialog, which is usually included in the gnome-utils package<br /> #<br /> # INSTALLATION: GNOME 1.4.x: copy this script to the ~/Nautilus/scripts<br /> #                       directory<br /> #               GNOME 2.x: copy to the ~/.gnome2/nautilus-scripts directory<br /> #<br /> # USAGE:        Select the files that you would like to display in Nautilus,<br /> #               right click, go to Scripts, and then select this script.<br /> #               You will then be asked to enter a Delay time.  This is the<br /> #               length of time that each image will be shown.  If you enter<br /> #               0, the image will be displayed until you either click on the<br /> #               image, hit the right arrow, hit N or n, or the space key.<br /> #               For more options, run "feh --help" (without quotation marks)<br /> #<br /> # VERSION INFO:<br /> #               0.1 (20020923) - Initial public release<br /> #<br /> # COPYRIGHT:    Copyright (C) 2002 Brian Connelly <connelly@purdue.edu><br /> #<br /> # LICENSE:      GNU GPL<br /> #<br /> ###############################################################################<br /> DELAY=$(gdialog --title "Slideshow Properties" --inputbox "Enter Delay (Seconds)" 20 50 0 2>&1) || exit<br /> DELAY=1<br /> if [ $DELAY -eq 0 ]; then<br /> feh --title "Slideshow" -rFx -S name $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> else<br /> feh --title "Slideshow" -rFx -S name -D $DELAY<br /> $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> fi<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/watermark ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/watermark<br /> <code><br /> #!/bin/bash<br /> #<br /> # watermark.sh<br /> # $Id: watermark,v 1.1 2004/10/03 10:52:21 ullgren Exp $<br /> #<br /> # Add a defined watermark to a series of pictures<br /> #</p> <p># Absolute Location of the Watermark file<br /> WM="/home/hajo/data/Pics/Var/watermark.gif"</p> <p>if [ ! -n "$1" ]<br /> then<br /> zenity --error --text "Please select Pics to be watermarked!"<br /> exit $E_BADARGS<br /> fi</p> <p>typeset -i CNT=1<br /> typeset -i CUR=0</p> <p>(<br /> for pic in "$@"<br /> do<br /> echo "#Watermarking $pic"</p> <p> composite -gravity SouthEast "$WM" "$pic" "$pic"</p> <p> CUR=$CNT*100/$#<br /> echo $CUR<br /> CNT=$CNT+1<br /> done<br /> ) | zenity --progress --auto-close --percentage=0<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Multimedia/XMMS_Enqueue ====</h3> <p>$ cat nautilus-scripts/Varios/Multimedia/XMMS_Enqueue<br /> <code><br /> #!/bin/bash<br /> # Description: Nautilus script that enqueues files in XMMS by the order selected<br /> #<br /> # Author: Celso Pinto <cpinto@yimports.com><br /> #<br /> # Copyright (C) 2003 Celso Pinto<br /> # Licence: GNU GPL<br /> #<br /> # Dependency: wc,bash,head,tail,xmms<br /> #</p> <p>#$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS - new line separated file paths; passed on by Nautilus on Gnome 2.2</p> <p>echo "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" > /tmp/xmmsselected<br /> numlines=`wc -l /tmp/cpinto.xmmsselected | awk '{print $1}'`</p> <p>for ((i=$numlines; i>0; i--))<br /> do<br /> mediafile=`head -n$i /tmp/xmmsselected | tail -n1`<br /> xmms -e $mediafile<br /> done</code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/bzip2 ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/bzip2<br /> <code><br /> #!/bin/sh<br /> #<br /> # BZIP2 wrapper for Nautilus Scripts menu.<br /> #<br /> # AUTHOR: Roberto Piscitello <robepisc@freemail.it><br /> # DATE: 21 May 2001<br /> # LICENSE: GPL<br /> #</p> <p># We need gdialog or xmessage to output error messages<br /> GDIALOG="/usr/bin/gdialog"<br /> XMESSAGE="/usr/bin/X11/xmessage"</p> <p>TMP_FILE=`tempfile`<br /> IFS="<br /> "</p> <p>trap "rm -f $TMP_FILE" EXIT</p> <p>for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do<br /> cd `dirname $F`<br /> if ! bzip2 `basename $F` 2> $TMP_FILE; then<br /> # Some error happened: beep and show an error message<br /> echo -e "\007"<br /> if [ -x $GDIALOG ]; then<br /> gdialog --title bzip2 --msgbox "`cat $TMP_FILE`." 20 100<br /> elif [ -x $XMESSAGE ]; then<br /> xmessage -buttons OK -file $TMP_FILE<br /> fi<br /> fi<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/converter ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/converter<br /> <code><br /> #!/bin/sh<br /> # Copyright (C) Sept 13, 2001 Shane Mueller <smueller@umich.edu><br /> # http://www-personal.umich.edu/~smueller/Nautilus-Scripts<br /> #<br /> # pprint: This script designed for use with the Nautilus File Manager<br /> # This script requires the unix utility enscript, and may require<br /> # modification based upon your local printing command.<br /> # It will either print directly to the default printer or<br /> # will generate a pretty file from the selected text files, and either<br /> # print to printer or generate files from selected files.<br /> #<br /> # This does file-type sensitive selection.</p> <p># This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU Library General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.<br /> #First, process each of the selected file</p> <p>#Change these to their proper system-dependent locations<br /> CONVERT_PATH=/usr/bin/ #Path to Imagemagick convert.<br /> ENSCRIPT_PATH=/usr/bin #Path to enscript utilities.<br /> OGG_PATH=/usr/bin/ #Pat to ogg utilities.<br /> GHOSTSCRIPT_PATH=/usr/bin #Path to ghostscript utilities.<br /> ALIEN_PATH=/usr/bin #Path to alien.<br /> LAME_PATH=/usr/bin #Path to LAME mp3 encoder<br /> ABI_PATH=/usr/bin #Path to abiword binary.<br /> UNRAR_PATH=/usr/local/bin #Path to unrar binary.<br /> UNZIP_PATH=/usr/bin #Path to unzip binary.<br /> UNACE_PATH=/usr/local/bin #Path to unace binary.<br /> UNARJ_PATH=/usr/bin #Path to unarj binary.<br /> BUNZIP2_PATH=/usr/bin #Path to bzip2 binary.<br /> GUNZIP_PATH=/usr/bin #Path to gunzip binary.<br /> TAR_PATH=/bin #Path to tar binary.</p> <p>for arg<br /> do<br /> FILETYPE=$(file "$arg")</p> <p> #Do file-type sensitive processing<br /> case "$FILETYPE" in<br /> *text*) #Any type of Text file<br /> #This allows you to select how the file is processed<br /> 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`</p> <p> case $choice in<br /> 1) ##print using enscript<br /> enscript -2 -G2rE -U1 --borders --word-wrap "$arg"<br /> ;;</p> <p> 2) ##print to a .ps file of your choice<br /> NEWNAME=`gdialog --title "Generate Postscript File" --inputbox "Enter Filename (include extension)" 200 100 "$arg".ps 2>&1`<br /> enscript -2 -G2rE -U1 --borders --word-wrap -p "$NEWNAME" "$arg"<br /> ;;</p> <p> 3) ##Generate an .html<br /> NEWNAME=`gdialog --title "Generate .html" --inputbox "Enter Filename (include extension)" 200 100 "$arg".html 2>&1`<br /> enscript -E --color -W html -p "$NEWNAME" "$arg"<br /> ;;</p> <p> 4) ##Generate an .rtf<br /> NEWNAME=`gdialog --title "Generate .rtf" --inputbox "Enter Filename (include extension)" 200 100 "$arg".rtf 2>&1`<br /> enscript -E -W rtf -p "$NEWNAME" "$arg"<br /> ;;</p> <p> *) ##Don't do nothing-cancel key<br /> ;;<br /> esac</p> <p> ##Other file types can go here if you know how to process them.<br /> *postscript*)</p> <p> *)<br /> gdialog --msgbox "Uncertain how to process file $arg: \n File type $filetype" 200 200</p> <p> esac</p> <p>done</code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/create_file ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/create_file<br /> <code><br /> #!/usr/bin/perl -w<br /> #<br /> # Released under the terms of GNU GPL v 2.0 or later<br /> #<br /> # Copyright (C) David Westlund<br /> #<br /> # You will need libgtk-perl to run this program.<br /> #<br /> # NOTE: This script is a little buggy, and doesn't operate as expected.<br /> # Please contribute any bugfixes to smueller@umich.edu.<br /> #<br /> # Config<br /> $template_directory = $ENV{HOME} . "/Nautilus/skript/.mallar/";</p> <p># For Gtk<br /> use Gtk;</p> <p>init Gtk;<br /> set_locale Gtk;</p> <p># For cwd, used to get the current directory<br /> use Cwd;</p> <p>my $true = 1;<br /> my $false = 0;</p> <p># These will be used as gtk-widgets<br /> my $window;<br /> my $vbox;<br /> my $hbox_1;<br /> my $hbox_2;<br /> my $filename_label;<br /> my $filename_entry;<br /> my $create_button;</p> <p># This are for the menu;<br /> my $opt;<br /> my $menu;<br /> my @menu_item;<br /> # Non-widgets for the menus...<br /> my $i;<br /> my $application;<br /> my $end;</p> <p>#Other variables<br /> my $cwd = cwd;</p> <p># The gtk-signals<br /> my $signal;</p> <p>$window = new Gtk::Window( 'toplevel' );<br /> $signal = $window->signal_connect( 'delete_event', sub { Gtk->exit( 0 ); } );<br /> $window->border_width( 5 );<br /> $window->set_title( "Create file" );</p> <p>$vbox = new Gtk::VBox ( $false, 0 );<br /> $window->add( $vbox );<br /> $vbox->show ();</p> <p>$hbox_1 = new Gtk::HBox ( $false, 0 );<br /> $vbox->pack_start ($hbox_1, $false, $false, 0);<br /> $hbox_1->show();</p> <p>$filename_label = new Gtk::Label ( "Filename: " );<br /> $hbox_1->pack_start ($filename_label, $false, $false, 0);<br /> $filename_label->show();</p> <p>$filename_entry = new Gtk::Entry ();<br /> $hbox_1->pack_start ($filename_entry, $false, $false, 0);<br /> $filename_entry->set_usize ( 100, undef );<br /> $filename_entry->show();</p> <p># Row nr two<br /> $hbox_2 = new Gtk::HBox ( $false, 0 );<br /> $vbox->pack_start ($hbox_2, $false, $false, 0);<br /> $hbox_2->show();</p> <p># Create the button<br /> $create_button = new Gtk::Button ( "Create file" );<br /> $create_button->signal_connect ('clicked', \&create_file );<br /> $hbox_2->pack_start ($create_button, $false, $false, 0);<br /> $create_button->show();</p> <p># Creating the menu<br /> $opt = new Gtk::OptionMenu ();<br /> $menu = new Gtk::Menu ();</p> <p>$i = 0;<br /> chdir $template_directory;<br /> while (<*>) {<br /> $application = $_;<br /> $end = $_;<br /> $application =~ s/\..*//;<br /> $end =~ s/$application//;</p> <p> $menu_item[$i] = new Gtk::MenuItem ( "$application" );<br /> $menu_item[$i]->signal_connect ( 'activate', \&create_app_file, $application, $end);<br /> $menu->append ($menu_item[$i]);<br /> $menu_item[$i]->show ();<br /> $i++;<br /> }<br /> $opt->set_menu ($menu);<br /> $opt->show ();</p> <p>$hbox_2->pack_start ($opt, $false, $false, 0);</p> <p>$window->show ();<br /> main Gtk;</p> <p>sub create_file<br /> {<br /> my $filename;</p> <p> $filename = $filename_entry->get_text ();</p> <p> $filename = $cwd . "\/$filename";</p> <p> system (": > $filename");</p> <p> Gtk->exit (0);<br /> }</p> <p>sub create_app_file<br /> {<br /> my ($info, $application, $end) = @_;<br /> my $filename;<br /> my $template;<br /> $filename = $filename_entry->get_text ();</p> <p> $filename = $filename . $end;<br /> $filename = $cwd . "\/$filename";</p> <p> $template = $application . $end;</p> <p> system ("cp $template_directory/$template $filename");</p> <p> Gtk->exit (0);<br /> }<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/create_targz ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/create_targz<br /> <code><br /> #!/bin/bash<br /> #<br /> # Nautilus script -> make one tar.gz with the selected files<br /> #<br /> # Owner : Largey Patrick Switzerland<br /> # naze.man@bluewin.ch<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Copyright (C) Nazeman<br /> #<br /> # Ver: 0.9.5-1<br /> # Some correction in gdialog with ver 0.9.4<br /> # thank's all for your job (sorry for my english)<br /> #<br /> # Ver: 0.9.4<br /> # Date: 11.05.2001<br /> # Support for swedish<br /> # Don't create files with names like archive.tar.gz.tar.gz or archive.tgz.tar.gz<br /> # If the input is just one file, the archive will be called <filename>.tar.gz as default<br /> # Added by David Westlund<br /> #<br /> # Ver: 0.9.3<br /> # Date: 10.09.2001<br /> # nazeman added file mit space !!!<br /> #<br /> # Ver: 0.9.2<br /> # Date: Sept 9, 2001<br /> # nazeman added confirm windows + German Support<br /> #<br /> #<br /> # Ver: 0.9.1<br /> # Date: Sept 5, 2001<br /> # Shane Mueller added patch from Manuel Clos to add Spanish support<br /> #<br /> # Ver : 0.9<br /> # Date : 11.08.2001<br /> #<br /> # Dependence : Nautilus (of course)<br /> # Gnome-utils (gdialog)<br /> #<br /> case $LANG in<br /> fr* )<br /> filename="Nom du Fichier ?"<br /> fileexist="Fichier existant, \E9craser ?"<br /> title="Archiveur "<br /> archive="archive"<br /> rec="est enregistr\E9" ;;<br /> es* )<br /> filename="\BFNombre del archivo?"<br /> fileexist="El archivo ya existe, \BFsobreescribir?"<br /> title="Archivar en tar.gz"<br /> archive="?????"<br /> rec="????" ;;<br /> de* )<br /> filename="Dateiname ?"<br /> fileexist="Datei existiert bereits, \FCberschreiben ?"<br /> title="Archiv erstellen"<br /> archive="archiv"<br /> rec="ist gespeichert" ;;<br /> sv* )<br /> filename="Filnamn?"<br /> fileexist="Filen existerar, vill du skriva \F6ver?"<br /> title="tar.gz-arkiverare"<br /> archive="arkiv"<br /> rec="\E4r sparad" ;;<br /> * )<br /> filename="File name ?"<br /> fileexist="File exist, owerwrite ?"<br /> title="tar.gz maker"<br /> archive="archive"<br /> rec="is saved" ;;<br /> esac<br /> if [ $# = 1 ]; then<br /> archive=`echo $1 | sed 's/.tar.gz//'`<br /> fi<br /> if<br /> nom=`gdialog --title "$title" --inputbox "$filename" 200 100 "$archive" 2>&1`<br /> then<br /> nom=`echo $nom | sed 's/.tar.gz//'`<br /> while [ -f ./$nom.tar.gz ]<br /> do<br /> if<br /> gdialog --title "$title" --defaultno --yesno "$fileexist" 200 100 ;<br /> then<br /> while [ $# -gt 0 ]<br /> do<br /> files=`echo "$1" | sed 's/ /\\ /g'`<br /> if [ -f ./$nom.tar ]<br /> then<br /> tar -rf ./$nom.tar "$files" ;<br /> else<br /> tar -cf ./$nom.tar "$files";<br /> fi<br /> shift<br /> done<br /> gzip -9f ./$nom.tar ;<br /> gdialog --msgbox "$PWD/$nom.tar.gz $rec" 200 100 ;<br /> exit 0 ;<br /> else<br /> if<br /> nom=`gdialog --title "$title" --inputbox "$filename" 200 100 "$archive" 2>&1`<br /> then<br /> continue ;<br /> else<br /> exit 0 ;<br /> fi<br /> fi<br /> done<br /> while [ $# -gt 0 ]<br /> do<br /> files=`echo "$1" | sed 's/ /\\ /g'`<br /> if [ -f ./$nom.tar ]<br /> then<br /> tar -rf ./$nom.tar "$files" ;<br /> else<br /> tar -cf ./$nom.tar "$files";<br /> fi<br /> shift<br /> done<br /> gzip -9 ./$nom.tar ;<br /> gdialog --msgbox "$PWD/$nom.tar.gz $rec" 200 100 ;<br /> fi<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/create-zip ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/create-zip<br /> <code><br /> #!/bin/sh<br /> # create-zip<br /> # From: Manuel Clos<br /> # Nautilus script -> make one zip with the selected file<br /> #<br /> # Dependence : Nautilus (of course)<br /> # Gnome-utils (gdialog)<br /> #<br /> case $LANG in<br /> es* )<br /> filename="\BFNombre del archivo?"<br /> fileexist="El archivo ya existe, \BFsobreescribir?"<br /> title="Archivar en zip" ;;<br /> fr* )<br /> filename="Nom du Fichier ?"<br /> fileexist="Fichier existant, \E9craser ?"<br /> title="Archiveur zip" ;;<br /> * )<br /> filename="File name ?"<br /> fileexist="File exist, owerwrite ?"<br /> title="zip maker" ;;<br /> esac<br /> if<br /> nom=`gdialog --title "$title" --inputbox "$filename " 200 100 2>&1`<br /> then<br /> while [ -f ./$nom.zip ]<br /> do<br /> if<br /> gdialog --title "$title" --defaultno --yesno "$fileexist" 200 100<br /> then<br /> zip -r ./$nom.zip $@ ;<br /> exit 0 ;<br /> else<br /> if<br /> nom=`gdialog --title "$title" --inputbox "$filename" 200 100 2>&1`<br /> then<br /> next ;<br /> else<br /> exit 0 ;</p> <p> fi<br /> fi<br /> done<br /> zip -r ./$nom.zip $@ ;<br /> fi</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/gb-unzip ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/gb-unzip<br /> <code><br /> #!/bin/sh<br /> #<br /> # GUNZIP and BUNZIP2 wrapper for Nautilus Scripts menu.<br /> #<br /> # AUTHOR: Roberto Piscitello <robepisc@freemail.it><br /> # DATE: 21 May 2001<br /> # LICENSE: GPL<br /> #</p> <p># We need gdialog or xmessage to output error messages<br /> GDIALOG="/usr/bin/gdialog"<br /> XMESSAGE="/usr/bin/X11/xmessage"</p> <p>TMP_FILE=`tempfile`<br /> IFS="<br /> "</p> <p>trap "rm -f $TMP_FILE" EXIT</p> <p>for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do<br /> cd `dirname $F`<br /> if [ `echo $F|awk '{ print substr($0,length($0)-2) }'` = "bz2" -o `echo $F|awk '{ print substr($0,length($0)-1) }'` = "bz" ]; then<br /> UZIP="bunzip2"<br /> else<br /> UZIP="gunzip"<br /> fi<br /> if ! $UZIP `basename $F` 2> $TMP_FILE; then<br /> # Some error happened: beep and show an error message<br /> echo -e "\007"<br /> if [ -x $GDIALOG ]; then<br /> gdialog --title $UZIP --msgbox "`cat $TMP_FILE`." 20 100<br /> elif [ -x $XMESSAGE ]; then<br /> xmessage -buttons OK -file $TMP_FILE<br /> fi<br /> fi<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/gzip ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/gzip<br /> <code><br /> #!/bin/sh<br /> #<br /> # GZIP wrapper for Nautilus Scripts menu.<br /> #<br /> # AUTHOR: Roberto Piscitello <robepisc@freemail.it><br /> # DATE: 21 May 2001<br /> # LINCENSE: GPL<br /> #</p> <p># We need gdialog or xmessage to output error messages<br /> GDIALOG="/usr/bin/gdialog"<br /> XMESSAGE="/usr/bin/X11/xmessage"</p> <p>TMP_FILE=`tempfile`<br /> IFS="<br /> "</p> <p>trap "rm -f $TMP_FILE" EXIT</p> <p>for F in $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS; do<br /> cd `dirname $F`<br /> if ! gzip `basename $F` 2> $TMP_FILE; then<br /> # Some error happened: beep and show an error message<br /> echo -e "\007"<br /> if [ -x $GDIALOG ]; then<br /> gdialog --title gzip --msgbox "`cat $TMP_FILE`." 20 100<br /> elif [ -x $XMESSAGE ]; then<br /> xmessage -buttons OK -file $TMP_FILE<br /> fi<br /> fi<br /> done</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/mail_image ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/mail_image<br /> <code><br /> #!/bin/sh</p> <p># FILE: mail_image --<br /> # AUTHOR: W. Michael Petullo <mike@flyn.org><br /> # DATE: 31 May 2001<br /> #<br /> # Copyright (C) 2001 W. Michael Petullo <mike@flyn.org><br /> # All rights reserved.<br /> #<br /> # This program is free software; you can redistribute it and/or modify<br /> # it under the terms of the GNU General Public License as published by<br /> # the Free Software Foundation; either version 2 of the License, or<br /> # (at your option) any later version.<br /> #<br /> # This program is distributed in the hope that it will be useful,<br /> # but WITHOUT ANY WARRANTY; without even the implied warranty of<br /> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br /> # GNU General Public License for more details.<br /> #<br /> # You should have received a copy of the GNU General Public License<br /> # along with this program; if not, write to the Free Software<br /> # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA</p> <p>tmpdir=`mktemp -d /tmp/mail-image-XXXXXX`</p> <p>for i in $*; do<br /> cp $i $tmpdir<br /> tmpfile=${tmpdir}/`basename $i`<br /> mogrify -geometry '640x480>' $tmpfile<br /> attachments=${attachments},${tmpfile}<br /> done</p> <p># Get rid of the leading comma.<br /> attachments=`echo $attachments | sed 's/^,//g'`</p> <p>balsa -a "$attachments"</p> <p>rm -rf $tmpdir<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/mailinbalsa ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/mailinbalsa<br /> <code><br /> #!/bin/sh</p> <p>for i in $*; do<br /> attachments=${attachments},${i}<br /> done</p> <p># Get rid of the leading comma.<br /> attachments=`echo $attachments | sed 's/^,//g'`</p> <p>balsa -a "$attachments"</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/RPM-install-update ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/RPM-install-update<br /> <code><br /> #!/bin/bash<br /> #<br /> # Nautilus script -> Install or Update Rpm with gnorpm<br /> #<br /> # Owner : Largey Patrick from Switzerland<br /> # patrick.largey@nazeman.org<br /> # www.nazeman.org<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Copyright (C) Nazeman<br /> #<br /> #<br /> # Ver: 1.0 Date: 31.03.2002<br /> # Initial release<br /> #<br /> # Dependence : Nautilus (of course)<br /> # Gdialog (Gnome-utils)<br /> # Gnome-Rpms (gnorpms)<br /> #<br /> title="Rpm Installer-Updater"<br /> rpminstaller="What do you want to make ?"<br /> install="install"<br /> update="update"<br /> info="information"<br /> case $LANG in<br /> fr* )<br /> title="Rpm installation ou mise \E0 jour"<br /> rpminstaller="Que voulez-vous faire ?"<br /> install="installation"<br /> update="mise \E0 jour"<br /> info="information";;<br /> esac </p> <p>filesall=""<br /> while [ $# -gt 0 ]<br /> do<br /> files=`echo "$1" | sed 's/ /\?/g'`<br /> filesall="$files $filesall"<br /> shift<br /> done<br /> admin=`whoami`<br /> if<br /> rpmchoise=`gdialog --title "$title" --radiolist "$rpminstaller" 260 100 5 "-i" "$install" off "-U" "$update" on "-qp" "$info" off 2>&1`<br /> then<br /> case $rpmchoise in<br /> -i )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -i $fileall&<br /> else<br /> gnorpm-auth -i $filesall&<br /> fi;;<br /> -U )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -U $fileall&<br /> else<br /> gnorpm-auth -U $filesall&<br /> fi;;<br /> -qp )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -qp $fileall&<br /> else<br /> gnorpm-auth -qp $filesall&<br /> fi;;<br /> esac<br /> else<br /> exit 0<br /> fi</code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/to_upper ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/to_upper<br /> <code><br /> #!/bin/sh</p> <p>echo $@<br /> # Lower-case a filename<br /> #Note that 'This' will overwrite 'this'!<br /> mv -iv "$@" "`echo \"$@\" | tr A-Z a-z`"<br /> </code></p> <h3> ==== nautilus-scripts/Varios/Obsolete/uncompress_all ====</h3> <p>$ cat nautilus-scripts/Varios/Obsolete/uncompress_all<br /> <code><br /> #!/bin/bash<br /> #<br /> # Nautilus script -> Un Compress all format<br /> #<br /> # tar.gz ; tgz ; tar ; gz ; tar.bz2 ; bz2 ; zip ; rar are know<br /> #<br /> # Owner : Largey Patrick from Switzerland<br /> # naze.man@bluewin.ch<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Copyright (C) Nazeman<br /> #<br /> # Ver: 0.9.2<br /> # Add rar format + error dialog<br /> #<br /> # Ver: 0.9.1<br /> # Date: 11.05.2001<br /> # Support for swedish<br /> # Added by David Westlund<br /> #<br /> # Ver: 0.9<br /> # Date: 27.10.2001<br /> #<br /> # Dependence : Nautilus (of course)<br /> # Gnome-utils (gdialog)<br /> #<br /> case $LANG in<br /> fr* )<br /> title="Decompacteur"<br /> beuh="format inconnu"<br /> ncompr="ne peut \EAtre d\E9compress\E9"<br /> compr="est d\E9compress\E9" ;;<br /> sv* )<br /> title="Packa upp"<br /> beuh="Ok\E4nt format"<br /> ncompr="kunde inte packas upp korrekt"<br /> compr="\E4r uppackad" ;;<br /> * )<br /> title="Uncompress"<br /> beuh="Unknown format"<br /> ncompr="could not be decompressed"<br /> compr="is decompressed" ;;<br /> esac<br /> decompressed=""<br /> errors=""<br /> while [ $# -gt 0 ]<br /> do<br /> error=0<br /> #<br /> # tar.gz format<br /> #<br /> if<br /> ext=`echo "$1" | grep [.]tar.gz$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -xzf "$1" || error=1<br /> #<br /> # tgz format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]tgz$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -xzf "$1" || error=1<br /> #<br /> # tar format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]tar$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -xf "$1" || error=1<br /> #<br /> # gz format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]gz$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> gunzip -N "$1" || error=1<br /> #<br /> # tar.bz2 format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]tar.bz2$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -jxf "$1" || error=1<br /> #<br /> # bz2 format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]bz2$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> bunzip2 -k "$1" || error=1<br /> #<br /> # zip format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]zip$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> unzip "$1" || error=1<br /> #<br /> # rar format<br /> #<br /> elif<br /> ext=`echo "$1" | grep [.]rar$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> unrar x -kb -o+ "$1" || error=1<br /> #<br /> # ??? format<br /> #<br /> else<br /> gdialog --title "$title" --msgbox "$1 $beuh" 200 100<br /> error=-1;<br /> fi </p> <p> if [ $error != -1 ]; then<br /> if [ $error = 0 ]; then<br /> decompressed="$decompressed $1"<br /> else<br /> errors="$errors $1"<br /> fi<br /> fi</p> <p> shift<br /> done</p> <p>if [ "$decompressed" != "" ]; then<br /> gdialog --title "$title" --msgbox "$decompressed $compr" 200 100<br /> fi</p> <p>if [ "$errors" != "" ]; then<br /> gdialog --title "$title" --msgbox "$errors $ncompr" 200 100<br /> fi<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/archiver-config ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/archiver-config<br /> <code><br /> #!/bin/bash<br /> #<br /> #<br /> # Nautilus script -> Config for Archive Tool for Nautilus<br /> # Make default config for archiver-unarchiver<br /> #<br /> # Owner : Largey Patrick Switzerland<br /> # patrick.largey@nazeman.org<br /> # www.nazeman.org<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Copyright (C) Nazeman<br /> #<br /> # Dependency : gdialog (gnome-utils) or Zenity<br /> # archiver-unarchiver ;-)<br /> #<br /> # Encoding UTF-8<br /> #<br /> # Ver 0.9.3 Date 13.12.2003<br /> # Add zenity ;-)<br /> #<br /> # Ver 0.9.2 Date 03,05,2003<br /> # Update for Gnome 2.x<br /> #<br /> # Ver 0.9-1 Date 20.03.2002<br /> # Some update and Brazilian portuguese from Rafael Rigues <rigues@terra.com.br><br /> #<br /> # Ver 0.9 Date : 11.03.2002<br /> # First release .... Configurator for archiver-unarchiver<br /> #<br /> title="Config for Archiver-Unarchiver"<br /> compressormulti="Default archiver format for multiple files : "<br /> compressorsingle="Default archiver format for single file : "<br /> valid="available"<br /> notvalid="not available"<br /> format="format"<br /> choix="choice"<br /> noconfig="no config"<br /> info="information"<br /> rec="was created successfully."<br /> case $LANG in<br /> fr* )<br /> title="Config de l'Archiveur-Desarchiveur"<br /> compressormulti="Format d'archive par défaut pour de multiples fichiers : "<br /> compressorsingle="Format d'archive par défaut pour fichier unique : "<br /> valid="disponible"<br /> notvalid="non disponible"<br /> format="extension"<br /> choix="choix"<br /> noconfig="ne pas configurer"<br /> info="information"<br /> rec="est enregistré";;<br /> de* )<br /> title="Konfigurator von Archiver-Desarchiver"<br /> compressormulti="Default Archiver Format für mehrere Dateien : "<br /> compressorsingle"Default archiver Format für ein Datei : "<br /> valid="Gültig"<br /> notvalid="Nicht gültig"<br /> format="Format"<br /> choix="Choice"<br /> noconfig="nicht konfigurieren"<br /> rec="ist gespeichert";;<br /> pt* )<br /> title="Configurador para o Compactador-Descompactador"<br /> compressormulti="Formato padrão para múltiplos arquivos : "<br /> compressorsingle="Formato padrão para um único arquivo : "<br /> valid="disponível"<br /> notvalid="não disponível"<br /> noconfig="não configurar"<br /> rec="foi criado com sucesso.";;<br /> es* )<br /> title="Configuración de Archivador-Desarchivador"<br /> compressormulti="Formato por defecto para varios ficheros : "<br /> compressorsingle="Formato por defecto para un solo fichero : "<br /> valid="disponible"<br /> notvalid="no disponible"<br /> noconfig="sin configuración"<br /> rec="se guardó correctamente";;<br /> esac<br /> #<br /> # Test binary programm<br /> #<br /> if which tar 2> /dev/null<br /> then<br /> atar="$valid"<br /> else<br /> atar="$notvalid"<br /> fi<br /> if which zip 2> /dev/null<br /> then<br /> azip="$valid"<br /> else<br /> azip="$notvalid"<br /> fi<br /> if which gzip 2> /dev/null<br /> then<br /> agzip="$valid"<br /> else<br /> agzip="$notvalid"<br /> fi<br /> if which bzip2 2> /dev/null<br /> then<br /> abzip2="$valid"<br /> else<br /> abzip2="$notvalid"<br /> fi<br /> if which compress 2> /dev/null<br /> then<br /> acompress="$valid"<br /> else<br /> acompress="$notvalid"<br /> fi<br /> if which rar 2> /dev/null<br /> then<br /> arar="$valid"<br /> else<br /> arar="$notvalid"<br /> fi<br /> #<br /> # Configure default extension for archiver-unarchiver<br /> #<br /> if which zenity 2>/dev/null<br /> then<br /> #<br /> # script with zenity<br /> #<br /> if<br /> 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`<br /> then<br /> compres=`echo $compres | sed 's/\"//g'`<br /> if [ "$compres" = "X" ]<br /> then<br /> echo "" > ~/.archiver.conf<br /> else<br /> echo "single $compres" > ~/.archiver.conf<br /> fi<br /> else<br /> exit 0<br /> fi<br /> if<br /> 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`<br /> then<br /> compres=`echo $compres | sed 's/\"//g'`<br /> if [ "$compres" = "X" ]<br /> then<br /> echo "" >> ~/.archiver.conf<br /> else<br /> echo "multi $compres" >> ~/.archiver.conf<br /> fi<br /> else<br /> exit 0<br /> fi<br /> zenity --title "$title" --info --text "~/.archiver.conf $rec"<br /> else<br /> #<br /> # script with gdialog<br /> #<br /> if<br /> 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`<br /> then<br /> compres=`echo $compres | sed 's/\"//g'`<br /> if [ "$compres" = "X" ]<br /> then<br /> echo "" > ~/.archiver.conf<br /> else<br /> echo "single $compres" > ~/.archiver.conf<br /> fi<br /> else<br /> exit 0<br /> fi<br /> if<br /> 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`<br /> then<br /> compres=`echo $compres | sed 's/\"//g'`<br /> if [ "$compres" = "X" ]<br /> then<br /> echo "" >> ~/.archiver.conf<br /> else<br /> echo "multi $compres" >> ~/.archiver.conf<br /> fi<br /> else<br /> exit 0<br /> fi<br /> gdialog --title "$title" --msgbox "~/.archiver.conf $rec" 100 100<br /> fi</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Debian_Package ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Debian_Package<br /> <code><br /> #!/bin/bash<br /> #<br /> # Version: 0.1<br /> #<br /> # This script is build to extract, install and get info about Debian packages (.deb:s)<br /> #<br /> # Distributed under the terms of GNU GPL version 2 or later<br /> #<br /> # Copyright (C) Pontus Ullgren <pontus-a-ullgren.com> #<br /> # Install in your Nautilus scripts directory.<br /> #<br /> # Credits goes to Keith Conger for his super-extractor Nautilus script which I used as<br /> # a template.<br /> #</p> <p>FILE_TYPE=$(file -b $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS|awk '{ print $1}')<br /> MIME_TYPE=$(file -b $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS)</p> <p>DEFAULT_DIR="./"`basename $1 .deb`<br /> DPKG_PATH=/usr/bin<br /> TEMP_FILE=`tempfile`<br /> XTERMPRG=/usr/bin/X11/xterm</p> <p>if [ "$FILE_TYPE" != "Debian" ]; then<br /> zenity --error --title "File error" --text "$1 is not a Debian package.\nIt is reported as: $MIME_TYPE ($FILE_TYPE)" 2>&1<br /> exit -1;<br /> fi</p> <p>TODO=$(zenity --list --radiolist --column "" --column "Action" TRUE "Extract package" FALSE "Install package" FALSE "Get info" 2>&1)</p> <p>if [ "$TODO" = "Extract package" ]; then<br /> DIR=$(zenity --title "Extract compressed file to..." --entry --text "Directory to extract to:" --entry-text "$DEFAULT_DIR" --width=500 2>&1)<br /> if [ $DIR ]; then<br /> mkdir $DIR<br /> $DPKG_PATH/dpkg-deb --vextract $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS $DIR/ > $TEMP_FILE<br /> zenity --text-info --title "Extraction Log" --filename $TEMP_FILE --width=500 --height=500 2>&1<br /> rm $TEMP_FILE<br /> else<br /> zenity --error --title "Action canceled" --text "Action canceled by the user." 2>&1<br /> fi<br /> elif [ "$TODO" = "Install package" ]; then<br /> echo "#!/bin/sh" > $TEMP_FILE<br /> echo "/bin/su -c \"$DPKG_PATH/dpkg --install $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS\"" >> $TEMP_FILE<br /> echo "echo Press enter to exit ..." >> $TEMP_FILE<br /> echo "read" >> $TEMP_FILE<br /> $XTERMPRG -T "Installing $1" -e /bin/sh $TEMP_FILE<br /> rm $TEMP_FILE<br /> elif [ "$TODO" = "Get info" ]; then<br /> $DPKG_PATH/dpkg-deb -I $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS > $TEMP_FILE<br /> zenity --text-info --title "Info about $1" --filename $TEMP_FILE --width=500 --height=500 2>&1<br /> rm $TEMP_FILE<br /> fi<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Hide_or_Show_Hidden_Files ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Hide_or_Show_Hidden_Files<br /> <code><br /> # From dredoz on gnomesupport.org<br /> #!/bin/sh</p> <p>OLDSTATE=$(gconftool-2 --get "/desktop/gnome/file_views/show_hidden_files")</p> <p>if [ "$OLDSTATE" == "false" ] ; then<br /> NEWSTATE="True"<br /> else<br /> NEWSTATE="False"<br /> fi</p> <p>gconftool-2 --set "/desktop/gnome/file_views/show_hidden_files" --type boolean $NEWSTATE<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Install_Galeon_Theme ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Install_Galeon_Theme<br /> <code><br /> #!/bin/bash<br /> #<br /> #<br /> # Nautilus script -> Install Galeon Theme (Uses Archiver-Unarchiver)<br /> #<br /> # Install Galeon Theme Owner: Matthew Hall<br /> # nyquist@ntlworld.com<br /> # http://people.ecsc.co.uk/~matt/<br /> #<br /> # Archiver-Unarchiver Owner : Largey Patrick Switzerland<br /> # naze.man@bluewin.ch<br /> # www.homepage.swissonline.ch/nazeman<br /> # Archiver-Unarchiver Co-Owner : David Westlund<br /> # daw@wlug.westbo.se<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Default language<br /> #<br /> filename="File name?"<br /> fileexist="File exists. Overwrite?"<br /> title="Archiver-Unarchiver"<br /> archive="archive"<br /> compressor="extension: archive: "<br /> decompressor="Do you want to uncompress: "<br /> valid="available"<br /> notvalid="not available"<br /> pleasewait="Please wait...."<br /> warning="Warning!"<br /> beuh="Unknown format."<br /> ncompr="could not be uncompressed."<br /> compr="has been uncompressed."<br /> rec="was created successfully."<br /> overwrite="The following files will be overwritten: "<br /> proceed=". Do you want to proceed?"<br /> theme="Theme"<br /> installer="Installer"<br /> installed="Installed"</p> <p>case $LANG in<br /> fr* )<br /> filename="Nom du Fichier ?"<br /> fileexist="Fichier existant, \E9craser ?"<br /> title="Archiveur-Desarchiveur"<br /> archive="archive"<br /> decompressor="Voulez vous d\E9sarchiver : "<br /> compressor="Extension de l'archive : "<br /> valid="disponible"<br /> notvalid="non disponible"<br /> pleasewait="Veuillez patientez ....."<br /> warning="! Attention !"<br /> beuh="format inconnu"<br /> ncompr="ne peut \EAtre d\E9compress\E9"<br /> compr="est d\E9compress\E9"<br /> rec="est enregistr\E9"<br /> overwrite="les fichiers suivant seront \E9cras\E9: "<br /> theme="Th\E8me"<br /> installer="Installateur"<br /> installed="Install\E9"<br /> proceed=". Voulez-vous poursuirvre ?" ;;<br /> es* )<br /> filename="\BFNombre del archivo?"<br /> fileexist="El archivo ya existe, \BFsobreescribir?"<br /> title="Archivar"<br /> archive="archivo"<br /> compressor="\BFextensi\F3n del archivo?"<br /> decompressor="\BF Quiere descomprimir "<br /> valid="disponible"<br /> notvalid="no disponible"<br /> pleasewait="Por favor, espere..."<br /> warning="\A1 Cuidado !"<br /> beuh="Formato desconocido"<br /> ncompr="no se puede descomprimir"<br /> compr="se descomprimi\F3 correctamente."<br /> rec="se cre\F3 correctamente"<br /> overwrite="los archivos suiguientes ser\E1n sobreescritos: "<br /> theme="Tema"<br /> installer="Instalador"<br /> installed="Instalado"<br /> proceed=". \BF Quiere continuar ?" ;;<br /> de* )<br /> filename="Dateiname ?"<br /> fileexist="Datei existiert bereits, \FCberschreiben ?"<br /> title="Archiver-Desarchiver"<br /> archive="archiv"<br /> compressor="Extension von Archiv : "<br /> decompressor="wollen Sie dekomprimieren : "<br /> valid="G\FCltig"<br /> notvalid="Nicht g\FCltig"<br /> pleasewait="Bitte warten ...."<br /> warning="! Warnung !"<br /> beuh="unbekanntes Format"<br /> ncompr="kann nicht dekomprimieren"<br /> compr="ist komprimiert"<br /> rec="ist gespeichert"<br /> overwrite="soll(en) diese Datei(en) \FCberschriebenerden: "<br /> theme="Thema"<br /> installer="Installateur"<br /> installed="Installiert"<br /> proceed="Wollen Sie weitermachen ?" ;;<br /> eo* )<br /> filename="Dosiera nomo?"<br /> fileexist="Dosiero ekzistas. \C6u superskribu?"<br /> title="Ar\B6igilo-Malar\B6ivigilo"<br /> archive="ar\B6ivo"<br /> compressor="Fina\BCo de la ar\B6ivo?"<br /> decompressor="\C6u vi volas malar\B6ivigi: "<br /> valid="havebla"<br /> notvalid="nehavebla"<br /> pleasewait="Bonvolu atendi..."<br /> warning="Avertu!"<br /> beuh="Nekonata formato"<br /> ncompr="Ne povis kompresigi"<br /> compr="estas kompresigita"<br /> rec="\F8uste kreita"<br /> overwrite="La sekvantaj dosieroj superskribi\F8os: "<br /> theme=""<br /> installer=""<br /> installed=""<br /> proceed=". \C6u vi volas procedi?";;<br /> pt* )<br /> filename="Nome do arquivo?"<br /> fileexist="O arquivo j\E1 existe. Sobrescrever?"<br /> title="Compactador-Descompactador"<br /> archive="arquivo"<br /> compressor="extens\E3o: arquivo: "<br /> decompressor="Voc\EA quer descompactar: "<br /> valid="dispon\EDvel"<br /> notvalid="n\E3o dispon\EDvel"<br /> pleasewait="Aguarde...."<br /> warning="Aviso!"<br /> beuh="Formato desconhecido."<br /> ncompr="n\E3o p\F4de ser descompactado."<br /> compr="foi descompactado."<br /> rec="foi criado com sucesso."<br /> overwrite="Os seguintes arquivos ser\E3o sobrescritos: "<br /> theme=""<br /> installer=""<br /> installed=""<br /> proceed=". Deseja continuar?" ;;<br /> sv* )<br /> filename="Filnamn?"<br /> fileexist="Filen existerar, vill du skriva \F6ver?"<br /> title="tar.gz-arkiverare"<br /> compressor="Fil\E4ndelse arkiv :"<br /> decompressor="Vill du packa upp : "<br /> archive="arkiv"<br /> #valid="????"<br /> #notvalid="????"<br /> pleasewait="Var god v\E4nta..."<br /> warning="! Varning !"<br /> beuh="Ok\E4nt format"<br /> ncompr="kunde inte packas upp korrekt"<br /> compr="\E4r uppackad"<br /> rec="\E4r sparad"<br /> overwrite="F\F6ljande filer kommer skrivas \F6ver: "<br /> theme=""<br /> installer=""<br /> installed=""<br /> proceed=". Vill du forts\E4tta?" ;;<br /> et* )<br /> filename="Faili nimi?"<br /> fileexist="Fail on juba olemas. Kas kirjutada \FCle?"<br /> title="Arhivaator"<br /> archive="arhiiv"<br /> compressor="laiend: arhiiv: "<br /> decompressor="Kas sa tahad lahti pakkida: "<br /> valid="v\F5imalik"<br /> notvalid="ei ole v\F5imalik"<br /> pleasewait="Palun oota...."<br /> warning="Hoiatus!"<br /> beuh="Tundmatu vorming."<br /> ncompr=": ei saa lahti pakkida."<br /> compr="lahti pakitud."<br /> rec="edukalt loodud."<br /> overwrite="J\E4rgnevad failid kirjutatakse \FCle: "<br /> theme=""<br /> installer=""<br /> installed=""<br /> proceed=". Kas tahad j\E4tkata?" ;;<br /> esac<br /> #<br /> # check the config file<br /> #<br /> if [ ! -f ~/.archiver.conf ]<br /> then echo "" > ~/.archiver.conf<br /> fi<br /> #<br /> # test archive or not<br /> #<br /> test_arch1=`file -b "$1" | grep 'archive'`<br /> test_arch2=`file -b "$1" | grep 'compress'`<br /> test_arch="$test_arch1$test_arch2"<br /> if [ "$test_arch" != "" ]<br /> then<br /> #<br /> # is one archive -> decompress<br /> #<br /> decompressed=""<br /> errors=""<br /> if gdialog --title "$title" --yesno "$decompressor $1 ?" 100 100<br /> then<br /> while [ $# -gt 0 ]<br /> do<br /> error=0<br /> if<br /> ext=`echo "$1" | grep [.][tT][aA][rR].[gG][zZ]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -xzf "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`</p> <p> elif<br /> ext=`echo "$1" | grep [.][tT][gG][zZ]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -xzf "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][tT][aA][rR]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -xf "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][gG][zZ]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> gunzip -fN "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][tT][aA][rR][.][bB][zZ]2$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> tar -jxf "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][bB][zZ]2$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> bunzip2 -fk "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][zZ][iI][pP]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> unzip -o "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][rR][aA][rR]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> unrar x -kb -o+ "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][zZ]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> uncompress -f "$1" || error=1<br /> dir=`ls | cut -f 2 -d 'z'`<br /> elif<br /> ext=`echo "$1" | grep [.][aA][cC][eE]$ 2>&1`<br /> [ "$ext" != "" ]<br /> then<br /> unace -e "$1" || error=1<br /> else<br /> gdialog --title "$title" --msgbox "$1 $beuh" 200 100<br /> error=-1<br /> fi<br /> if [ $error != -1 ]<br /> then<br /> if [ $error = 0 ]<br /> then<br /> decompressed="$decompressed $1"<br /> else<br /> errors="$errors $1"<br /> fi<br /> fi<br /> shift<br /> done<br /> else<br /> exit 0<br /> fi<br /> else </p> <p>#<br /> # test if programm are availlable<br /> #<br /> if which tar 2> /dev/null<br /> then<br /> atar="$valid"<br /> else<br /> atar="$notvalid"<br /> fi<br /> if which zip 2> /dev/null<br /> then<br /> azip="$valid"<br /> else<br /> azip="$notvalid"<br /> fi<br /> if which gzip 2> /dev/null<br /> then<br /> agzip="$valid"<br /> else<br /> agzip="$notvalid"<br /> fi<br /> if which bzip2 2> /dev/null<br /> then<br /> abzip2="$valid"<br /> else<br /> abzip2="$notvalid"<br /> fi<br /> if which compress 2> /dev/null<br /> then<br /> acompress="$valid"<br /> else<br /> acompress="$notvalid"<br /> fi<br /> if which rar 2> /dev/null<br /> then<br /> arar="$valid"<br /> else<br /> arar="$notvalid"<br /> fi<br /> fi</p> <p>#Copy unpackaged theme to galeon theme directory</p> <p>admin=`whoami`<br /> if [ $admin = root ]<br /> then<br /> cp -R $dir /usr/share/galeon/themes/<br /> else<br /> if [ -d ~/.galeon/themes ]<br /> then<br /> mv $dir ~/.galeon/themes/$dir<br /> else<br /> mkdir ~/galeon/themes<br /> mv $dir ~/.galeon/themes/$dir<br /> fi<br /> fi</p> <p>#optionally remove directory (off by default)<br /> #rm -rf $dir</p> <p>#optionally remove package (off by default)<br /> #rm -f $1</p> <p> if [ "$decompressed" != "" ]<br /> then<br /> gdialog --title "Galeon $theme $installer & $title" --msgbox "$theme $installed" 200 100<br /> fi<br /> if [ "$errors" != "" ]<br /> then<br /> gdialog --title "$title" --msgbox "$errors $ncompr" 200 100<br /> fi</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/install_rpm ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/install_rpm<br /> <code><br /> #!/bin/bash<br /> gnorpm-auth -U $*<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Install_to_Palm ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Install_to_Palm<br /> <code><br /> #!/bin/sh<br /> # Nautilus Script to install an application on your Palm<br /> # Author: Andrea Grandi <andy80@ptlug.org><br /> # version: 0.1.0</p> <p>filepath=$NAUTILUS_SCRIPT_SELECTED_URIS</p> <p>gdialog --msgbox "I'm going to install $filepath on your Palm." 100 300</p> <p>gpilot-install-file -n $filepath</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/make_launcher ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/make_launcher<br /> <code><br /> #!/bin/sh<br /> # Make lancher - Script to create a .desktop launcher at your Gnome desktop<br /> # By Terje Tollefsen</p> <p>makelancher() {<br /> lname=`gdialog --inputbox "Lancher $arg name" 200 100 "$arg" 2>&1`</p> <p> if [ $? -eq 1 ]; then<br /> exit<br /> fi</p> <p> lcomment=`gdialog --inputbox "Lancher $arg comment" 200 100 "$arg" 2>&1`</p> <p> if [ $? -eq 1 ]; then<br /> exit<br /> fi</p> <p> licon=`gdialog --inputbox "Lancher $arg icon" 200 100 "gnome-ccdesktop.png" 2>&1`</p> <p> if [ $? -eq 1 ]; then<br /> exit<br /> fi</p> <p> echo [Desktop Entry] > ~/.gnome-desktop/"$arg.desktop"<br /> echo Name=$lname >> ~/.gnome-desktop/"$arg.desktop"<br /> echo Comment=$lcomment >> ~/.gnome-desktop/"$arg.desktop"<br /> echo Exec=$PWD/$lexec >> ~/.gnome-desktop/"$arg.desktop"<br /> echo Icon=$licon >> ~/.gnome-desktop/"$arg.desktop"<br /> echo Terminal=0 >> ~/.gnome-desktop/"$arg.desktop"<br /> echo Type=Application >> ~/.gnome-desktop/"$arg.desktop"<br /> }</p> <p>for arg<br /> do</p> <p> lexec=$arg</p> <p> if [ -f ~/.gnome-desktop/"$arg.desktop" ];<br /> then<br /> if gdialog --title "Overwrite?" --defaultno --yesno "Launcher $arg already exist. Overwrite?" 200 100<br /> then<br /> makelancher<br /> else<br /> arg=`gdialog --inputbox ".desktop filename for $arg" 200 100 "New-$arg" 2>&1`</p> <p> if [ $? -eq 1 ]; then<br /> exit<br /> fi</p> <p> makelancher<br /> fi<br /> else<br /> makelancher<br /> fi<br /> done<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/make-nautilus-script ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/make-nautilus-script<br /> <code><br /> #!/bin/sh<br /> # make_nautilus_script: copies the selected file(s) to ~/Nautilus/scripts<br /> # and makes it executable. It will overwrite without warning.<br /> for arg<br /> do</p> <p> cp "$arg" ~/.gnome/nautilus-scripts/<br /> chmod u+x ~/.gnome/nautilus-scripts/"$arg"</p> <p>done</code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/pseudo-nautilus ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/pseudo-nautilus<br /> <code><br /> #/bin/bash<br /> ## This is a "PSEUDO-NAUTILUS" general script.<br /> ## To run a "Nautilus" script without Nautilus, change COMMAND<br /> ## to the script of your choice. This will set all important<br /> ## environment variables that a script is likely to use, as<br /> ## well as assuring the script executes in the proper directory<br /> ##<br /> ## To use: Create a launcher in the panel, or a .desktop file that executes<br /> ## this script. By dragging selected files to this launcher, the script<br /> ## will run on the selected files in the directory of the files.<br /> ##<br /> ##<br /> ## Placed in the public domain April, 2002 by Shane T. Mueller<br /> ##<br /> ##<br /> ## Version 1.1 Apr 5, 2002 Additional fixes for files with spaces in their names, with<br /> thanks to Patrick Largey.<br /> ## Version 1.0 April 1, 2002 Initial Release.<br /> SCRIPTNAME=~/.gnome/nautilus-scripts/scriptname</p> <p>shortnames=""<br /> longnames=""<br /> urls=""</p> <p>for arg in "$@"<br /> do<br /> #Make sure that the url starts with the proper type: if the url starts with<br /> ## '/', change it to 'file:///'<br /> url=`echo "$arg"| sed 's/^\//file:\/\/\//'`</p> <p> ##find the long name of the file (absolute path)<br /> longname=`echo "$url" | sed -e 's/file:\/\///g'`</p> <p> ## This crazy line translates all of the %20-like url characters into their escaped<br /> ## \ actual characters. I wish I could find a cleaner way to do this.<br /> 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/\%3E/\>/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'`<br /> # This translation doesn't work.<br /> # -e 's/\%5C/\\/g'`</p> <p> ##find the short name of the file (filename only)<br /> shortname=`basename "$longname"`</p> <p> ##Mush the individual entries into a single strings<br /> urls="$url $urls"<br /> shortnames="$shortname $shortnames"<br /> longnames="$longname $longnames"<br /> done</p> <p>## extract the base URI<br /> URI=`echo "$1" | sed -e 's/\/[^\/]*$//' -e 's/^\//file:\/\/\//'`</p> <p>## Find the directory of the first item and go there<br /> DIR=`echo "$1" | sed -e 's/^file:\/\///g'`<br /> DIR=`dirname "$DIR"`<br /> cd $DIR</p> <p>#Export the environment variables that nautilus sets<br /> export NAUTILUS_SCRIPT_SELECTED_FILE_PATHS=$longnames<br /> export NAUTILUS_SCRIPT_SELECTED_URIS=$urls<br /> export NAUTILUS_SCRIPT_CURRENT_URI=$URI<br /> export NAUTILUS_SCRIPT_WINDOW_GEOMETRY="800x500+10+10"</p> <p>#Execute the proper script if anything was actually passed to this script<br /> if [ -n "$1" ]<br /> then<br /> "$SCRIPTNAME" $shortnames<br /> fi</code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/pynautilus ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/pynautilus<br /> <code><br /> #!/usr/bin/env python</p> <p>"""<br /> This function extracts Nautilus variables from the environment, splits them on<br /> newlines and puts results in dictionary.</p> <p>Example:</p> <p> ala = parse_nautilus_environment()</p> <p> for tmp in ala['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS']:<br /> print tmp</p> <p>"""</p> <p>def parse_nautilus_environment():<br /> import os</p> <p> result = {<br /> 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' : [],<br /> 'NAUTILUS_SCRIPT_SELECTED_URIS' : [],<br /> 'NAUTILUS_SCRIPT_CURRENT_URI' : [],<br /> 'NAUTILUS_SCRIPT_WINDOW_GEOMETRY' : [] # I wonder if anyone uses it ;)<br /> }</p> <p> for i in result.keys():<br /> if os.environ.has_key(i):<br /> result[i] = os.environ[i].split(':')<br /> else:<br /> result[i] = []</p> <p> return result</p> <p></code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Query_RPM ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Query_RPM<br /> <code><br /> #!/bin/sh<br /> quoted=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | awk 'BEGIN {<br /> FS = "\n" } { printf "\"%s\" ", $1 }' | sed -e s#\"\"##)<br /> eval "gnorpm -q -p $quoted"</code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/RPM-install-update ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/RPM-install-update<br /> <code><br /> #!/bin/bash<br /> #<br /> # Nautilus script -> Install or Update Rpm with gnorpm<br /> #<br /> # Owner : Largey Patrick from Switzerland<br /> # patrick.largey@nazeman.org<br /> # www.nazeman.org<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Copyright (C) Nazeman<br /> #<br /> #<br /> # Ver: 1.0 Date: 31.03.2002<br /> # Initial release<br /> #<br /> # Dependence : Nautilus (of course)<br /> # Gdialog (Gnome-utils)<br /> # Gnome-Rpms (gnorpms)<br /> #<br /> title="Rpm Installer-Updater"<br /> rpminstaller="What do you want to make ?"<br /> install="install"<br /> update="update"<br /> info="information"<br /> case $LANG in<br /> fr* )<br /> title="Rpm installation ou mise \E0 jour"<br /> rpminstaller="Que voulez-vous faire ?"<br /> install="installation"<br /> update="mise \E0 jour"<br /> info="information";;<br /> esac </p> <p>filesall=""<br /> while [ $# -gt 0 ]<br /> do<br /> files=`echo "$1" | sed 's/ /\?/g'`<br /> filesall="$files $filesall"<br /> shift<br /> done<br /> admin=`whoami`<br /> if<br /> rpmchoise=`gdialog --title "$title" --radiolist "$rpminstaller" 260 100 5 "-i" "$install" off "-U" "$update" on "-qp" "$info" off 2>&1`<br /> then<br /> case $rpmchoise in<br /> -i )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -i $fileall&<br /> else<br /> gnorpm-auth -i $filesall&<br /> fi;;<br /> -U )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -U $fileall&<br /> else<br /> gnorpm-auth -U $filesall&<br /> fi;;<br /> -qp )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -qp $fileall&<br /> else<br /> gnorpm-auth -qp $filesall&<br /> fi;;<br /> esac<br /> else<br /> exit 0<br /> fi</code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/RPM-tools ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/RPM-tools<br /> <code><br /> #!/bin/bash<br /> #<br /> # Nautilus script -> Install or Update Rpm with gnorpm<br /> #<br /> # Owner : Largey Patrick from Switzerland<br /> # patrick.largey@nazeman.org<br /> # www.nazeman.org<br /> #<br /> # Licence : GNU GPL<br /> #<br /> # Copyright (C) Nazeman<br /> #<br /> # Ver: 1.04<br /> # Remove nodeps option don't work with gnorpm<br /> #<br /> # Ver: 1.03<br /> # Add check if one Rpm is selected or not<br /> #<br /> # Ver: 1.02<br /> # Add spanish translation by Manuel Clos <llanero@jazzfree.com><br /> #<br /> # Ver: 1.01<br /> # Bug fix with user root + add possibilty to install or update with nodeps<br /> #<br /> # Ver: 1.0 Date: 31.03.2002<br /> # Initial release<br /> #<br /> # Dependence : Nautilus (of course)<br /> # Gdialog (Gnome-utils)<br /> # Gnome-Rpms (gnorpms)<br /> #<br /> title="Rpm Installer-Updater"<br /> rpminstaller="What do you want to make ?"<br /> install="install"<br /> update="update"<br /> info="information"<br /> dontrpm="That's not a RPM package !"<br /> case $LANG in<br /> fr* )<br /> title="Rpm installation ou mise \E0 jour"<br /> rpminstaller="Que voulez-vous faire ?"<br /> install="installation"<br /> update="mise \E0 jour"<br /> info="information"<br /> dontrpm="Ce n'est pas un paquet RPM !";;<br /> es* )<br /> title="Instalador-Actualizador de Rpm"<br /> rpminstaller="\BF Qu\E9 desea hacer ?"<br /> install="instalar"<br /> update="actualizar"<br /> info="informaci\F3n";;<br /> esac </p> <p>filesall=""<br /> testrpm=`file -b "$1" | grep 'RPM'`<br /> while [ $# -gt 0 ]<br /> do<br /> files=`echo "$1" | sed 's/ /\?/g'`<br /> filesall="$files $filesall"<br /> shift<br /> done<br /> admin=`whoami`<br /> if [ "$testrpm" != "" ]<br /> then<br /> if<br /> rpmchoise=`gdialog --title "$title" --radiolist "$rpminstaller" 200 150 9 "-i" "$install" off "-U" "$update" on "-qp" "$info" off 2>&1`<br /> then<br /> case $rpmchoise in<br /> -i )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -i $filesall&<br /> else<br /> gnorpm-auth -i $filesall&<br /> fi;;<br /> -U )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -U $filesall&<br /> else<br /> gnorpm-auth -U $filesall&<br /> fi;;<br /> -qp )<br /> if [ $admin = root ]<br /> then<br /> gnorpm -qp $filesall&<br /> else<br /> gnorpm-auth -qp $filesall&<br /> fi;;<br /> esac<br /> else<br /> exit 0<br /> fi<br /> else<br /> gdialog --title "$title" --msgbox "$dontrpm" 250 100<br /> fi </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Set_as_Directory_Icon ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Set_as_Directory_Icon<br /> <code><br /> #!/usr/bin/perl<br /> #<br /> # Nautilus Script:<br /> # Set selected image as the current directory's icon<br /> #<br /> # Owner:<br /> # Barak Korren<br /> # ifireball@yahoo.com<br /> #<br /> # Licence: GNU GPL<br /> # Copyright (C) Barak Korren<br /> #<br /> # Change log:<br /> # Mon, Apr 05, 2004 - Created.<br /> #<br /> # Known Issues:<br /> # Nautilus needs to be restarted for changes to take effect.<br /> # The file set is the icon is arbitarily the last one passed by Nautilus.<br /> # No filetype checking is performed.<br /> #</p> <p>use XML::LibXML;</p> <p>sub urify($) {<br /> my $str = shift;<br /> $str =~ s/([\/% ])/sprintf("%%%X", ord($1))/eg;<br /> return $str;<br /> }</p> <p>sub errorquit($) {<br /> exec "zenity --error --text='${_[0]}'";<br /> exit;<br /> }</p> <p>$su = $ENV{'NAUTILUS_SCRIPT_SELECTED_URIS'}<br /> or die('This script must be run from Nautilus!');<br /> $cu = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'}<br /> or die('This script must be run from Nautilus!');</p> <p>($icon) = ($su =~ m/([^\n]*$)/);<br /> ($metafile,$dir) = ($cu =~ m/(.*)\/([^\/]+)/);<br /> $metafile = $ENV{'HOME'} . "/.nautilus/metafiles/" . urify($metafile) . ".xml";</p> <p>if (-e $metafile) {<br /> find mu # If metafile exists, verify we can<br /> # read and write it, then parse it<br /> if( -r $metafile && -w $metafile) {<br /> $mf = XML::LibXML->new()->parse_file($metafile);<br /> $de = $mf->documentElement();<br /> }<br /> else {<br /> errorquit("Can't edit metafile:\n$metafile");<br /> }<br /> }<br /> else {<br /> # If Metafile doesn't exist, make one<br /> $mf = XML::LibXML::Document->new();<br /> $de = $mf->createElement('directory');<br /> $mf->setDocumentElement($mf);<br /> }</p> <p># See if we got a <file> element for the directory<br /> if(@nodes = $de->findnodes("file[\@name=\"$dir\"]")) {<br /> $fe = @nodes[0];<br /> }<br /> else {<br /> # If there isn't an element make it<br /> $fe = $mf->createElement("file");<br /> $fe->setAttribute("name", $dir);<br /> $de->appendChild($fe);<br /> }</p> <p># Finally, set the custom_icon attribute<br /> $fe->setAttribute("custom_icon", $icon);</p> <p># Now save our work<br /> $mf->toFile($metafile, 0);<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Set_as_Wallpaper ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Set_as_Wallpaper<br /> <code><br /> #!/bin/sh<br /> # From Tuomos Kuosmanen on the Nautilus Mailing List<br /> background-properties-capplet --init-session-settings --background-image="`pwd`/$1"<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Set_image_as_Wallpaper ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Set_image_as_Wallpaper<br /> <code><br /> #!/bin/bash</p> <p>###############################################################################<br /> # Display a fullscreen slideshow of the selected files<br /> ###############################################################################<br /> #<br /> # AUTHOR: Karl Bowden <kbowden@pacificspeed.com.au><br /> #<br /> # CREDITS: Brian Connelly <pub@bconnelly.net> - For the slideshow script<br /> # that I based this script on.<br /> #<br /> # DESCRIPTION: This script sets the background in Gnome2 the the selected<br /> # filename.<br /> #<br /> # REQUIREMENTS: Nautilus file manager<br /> # Gnome2<br /> # gdialog, which is usually included in the gnome-utils package<br /> #<br /> # INSTALLATION: copy to the ~/.gnome2/nautilus-scripts directory<br /> #<br /> # USAGE: Select the file that you would like to use as your wallpaper<br /> # in Nautilus, right click, go to Scripts, and then select this<br /> # script. You will then be asked to selest how you would like<br /> # the image displayed.<br /> #<br /> # VERSION INFO:<br /> # 0.1 (20020928) - Initial public release<br /> #<br /> # COPYRIGHT: Copyright (C) 2002 Karl Bowden <kbowden@pacificspeed.com.au><br /> #<br /> # LICENSE: GNU GPL<br /> #<br /> ###############################################################################</p> <p>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)</p> <p>if [ $WALLPAPER = "1" ]; then<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_options wallpaper<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> fi<br /> if [ $WALLPAPER = "2" ]; then<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_options centered<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> fi<br /> if [ $WALLPAPER = "3" ]; then<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_options scaled<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> fi<br /> if [ $WALLPAPER = "4" ]; then<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_options stretched<br /> gconftool-2 --type=string --set /desktop/gnome/background/picture_filename $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS<br /> fi<br /> </code></p> <h3> ==== nautilus-scripts/Varios/SystemConfiguration/Show_Directory_Metafile ====</h3> <p>$ cat nautilus-scripts/Varios/SystemConfiguration/Show_Directory_Metafile<br /> <code><br /> #!/usr/bin/perl<br /> #<br /> # Nautilus Script:<br /> # Show the current directory's XML metafile.<br /> #<br /> # Owner:<br /> # Barak Korren<br /> # ifireball@yahoo.com<br /> #<br /> # Licence: GNU GPL<br /> # Copyright (C) Barak Korren<br /> #<br /> # Dependency:<br /> # zenity, xmllint, xmessage<br /> #<br /> # Change log:<br /> # Mon, Apr 05, 2004 - Created.<br /> #<br /> # Known Issues:<br /> # I'd like to use zentity instead of xmessage, but it doesn't currently<br /> # support showing text from the standard input, too bad gless doesn't seem<br /> # to be shipped with gnome-utils anymore, maybe one can use the builtin<br /> # Nautilus text viewer?<br /> #</p> <p>sub urlify($) {<br /> my $str = shift;<br /> $str =~ s/([\/% ])/sprintf("%%%X", ord($1))/eg;<br /> return $str;<br /> }</p> <p>$MFN = $ENV{'NAUTILUS_SCRIPT_CURRENT_URI'}<br /> or die('This script must be run from Nautilus!');<br /> $MFN = $ENV{'HOME'} . "/.nautilus/metafiles/" . urlify($MFN) . ".xml";</p> <p>if ( -r $MFN ) {<br /> exec "xmllint --format $MFN | xmessage -file -";<br /> }<br /> else {<br /> exec "zenity --error --text='Not Found:\n $MFN'";<br /> }<br /> </code></p> <h3> ==== nums ====</h3> <p>$ cat nums<br /> <code><br /> 1</p> <p>2</p> <p>3<br /> </code></p> <h3> ==== octais1.sh ====</h3> <p>$ cat octais1.sh<br /> <code><br /> #!/bin/sh<br /> #<br /> # Lista os caracteres entre \0000 e \0377 gerados pelo echo no octal correspondente<br /> # Caso receba a opcao -tn, para n variando de 1 a 9 a listagem serah temporizada<br /> #</p> <p>tp=0<br /> [ `echo "$1" | sed -n '/^-[tT][1-9]$/p'` ] && tp=`expr substr $1 3 1 \* 20`</p> <p>[ $tp -eq 0 -a $# -gt 0 ] &&<br /> {<br /> echo "Uso $0 [-tn] onde n \0351 um temporizador entre 1 e 9"<br /> exit 1<br /> }</p> <p>for i in 0 1 2 3<br /> do<br /> for j in 0 1 2 3 4 5 6 7<br /> do<br /> for k in 0 1 2 3 4 5 6 7<br /> do<br /> echo "0$i$j$k=\0$i$j$k\t\c"<br /> tp1=0<br /> while [ $tp1 -lt $tp ]<br /> do<br /> tp1=`expr $tp1 + 1`<br /> done<br /> [ $k -eq 7 ] && echo<br /> done<br /> done<br /> done<br /> </code></p> <h3> ==== octais2.sh ====</h3> <p>$ cat octais2.sh<br /> <code><br /> #! /bin/bash<br /> #<br /> # Lista os caracteres entre \0000 e \0377 gerados pelo echo no octal correspondente<br /> # Caso receba a opcao -tn, para n variando de 1 a 9 a listagem serah temporizada<br /> #</p> <p>loop1='0 1 2 3'<br /> loop2='0 1 2 3 4 5 6 7'<br /> set -A array 0 1 2 3 4 5 6 7</p> <p>echo " ${array[0]} ${array[1]} ${array[2]} ${array[3]}\<br /> ${array[4]} ${array[5]} ${array[6]} ${array[7]} "<br /> echo</p> <p>for i in $loop1<br /> do<br /> for j in $loop2<br /> do<br /> echo "$i$j \0$i$j${array[0]} \0$i$j${array[1]}\<br /> \0$i$j${array[2]} \0$i$j${array[3]} \0$i$j${array[4]}\<br /> \0$i$j${array[5]} \0$i$j${array[6]} \0$i$j${array[7]}"<br /> done<br /> done</p> <p>echo<br /> echo " ${array[0]} ${array[1]} ${array[2]} ${array[3]}\<br /> ${array[4]} ${array[5]} ${array[6]} ${array[7]} "<br /> echo<br /> </code></p> <h3> ==== param1 ====</h3> <p>$ cat param1<br /> <code><br /> echo $1<br /> echo $2<br /> echo $11<br /> </code></p> <h3> ==== param2 ====</h3> <p>$ cat param2<br /> <code><br /> echo $0<br /> echo $2<br /> echo ${11}<br /> </code></p> <h3> ==== param3 ====</h3> <p>$ cat param3<br /> <code><br /> echo O programa $0 Recebeu $# Parametros<br /> echo $1<br /> echo $2<br /> echo ${11}<br /> </code></p> <h3> ==== param4 ====</h3> <p>$ cat param4<br /> <code><br /> echo O Programa $0 Recebeu $# Parametros Listados Abaixo:<br /> echo $*<br /> </code></p> <h3> ==== param5 ====</h3> <p>$ cat param5<br /> <code><br /> echo O programa $0 Recebeu $# Parametros<br /> echo $1<br /> echo $2<br /> shift 10<br /> echo $1<br /> </code></p> <h3> ==== param6 ====</h3> <p>$ cat param6<br /> <code><br /> echo O programa $0 Recebeu $# Parametros<br /> echo -n "Que sao: "<br /> for i<br /> do<br /> echo -n "$i "<br /> done<br /> </code></p> <h3> ==== param7 ====</h3> <p>$ cat param7<br /> <code><br /> #!/bin/bash<br /> # Programa para testar passagem de parametros (3a. Versao)<br /> echo O programa $(basename $0) recebeu $# parametros<br /> echo "11o. parm (errado)-> $11"<br /> echo "10o. parm (certo) ${10}"<br /> echo "11o. parm (certo) ${11}"<br /> shift<br /> echo "2o. parm -> $1"<br /> shift 2<br /> echo "4o. Parm -> $1"<br /> </code></p> <h3> ==== passwd.tmp ====</h3> <p>$ cat passwd.tmp<br /> <code><br /> bin:x:2:2:bin:/bin:/bin/sh<br /> pulse:x:109:114:PulseAudio daemon,,,:/var/run/pulse:/bin/false<br /> rtkit:x:110:117:RealtimeKit,,,:/proc:/bin/false<br /> saned:x:111:118::/home/saned:/bin/false<br /> hplip:x:112:7:HPLIP system user,,,:/var/run/hplip:/bin/false<br /> gdm:x:113:120:Gnome Display Manager:/var/lib/gdm:/bin/false<br /> julio:x:1000:1000:Julio Neves,,,:/home/julio:/bin/bash<br /> postfix:x:114:123::/var/spool/postfix:/bin/false<br /> </code></p> <h3> ==== pedi ====</h3> <p>$ cat pedi<br /> <code><br /> #<br /> # Testa a resposta a um pedido. Deve ser (S)im ou (N)ao - Versao 3<br /> #</p> <p>if test $# = 0<br /> then<br /> echo Faltou informar a resposta<br /> exit 1<br /> fi<br /> resp=$1<br /> if test "$resp" = N<br /> then<br /> echo Ela nao deixa...<br /> elif test "$resp" = S<br /> then<br /> echo Oba, ela deixou!!!<br /> else<br /> echo Acho que ela esta na duvida.<br /> fi<br /> </code></p> <h3> ==== pp ====</h3> <p>$ cat pp<br /> <code><br /> #<br /> # Pesquisa Pessoa no Catalogo Telefonico - versao 2<br /> #</p> <p>grep "$1" telefones<br /> </code></p> <h3> ==== pp.awk ====</h3> <p>$ cat pp.awk<br /> <code><br /> awk '/'$1'/' telefones<br /> </code></p> <h3> ==== quebralingua.txt ====</h3> <p>$ cat quebralingua.txt<br /> <code><br /> Eu vi um velho com um fole velho nas costas.<br /> Tanto fede o fole do velho,<br /> quanto o velho do fole fede.<br /> </code></p> <h3> ==== quequeisso ====</h3> <p>$ cat quequeisso<br /> <code><br /> ATENCAO, O TEXTO ABAIXO NAO EH TREINAMENTO,<br /> EH UMA LAVAGEM CEREBRAL!!!<br /> O Shell alem de analisar cada dado entrado a partir do prompt do UNIX,<br /> interfaceando com os usuarios, tem tambem as seguintes atribuicoes:<br /> Interpretador de comandos;<br /> Controle do ambiente UNIX;<br /> Redirecionamento de entrada e saida;<br /> Substituicao de nomes de arquivos;<br /> Concatenacao de pipe;<br /> Execucao de programas;<br /> Poderosa linguagem de programacao.<br /> </code></p> <h3> ==== quero ====</h3> <p>$ cat quero<br /> <code><br /> quero-quero<br /> quero quero<br /> come-come<br /> bate-bate<br /> batebate<br /> rebate-bate<br /> rebate-bateria<br /> queroquero<br /> comecome<br /> bate-bateria<br /> hoje-joia<br /> come come<br /> bole--bole<br /> come come<br /> </code></p> <h3> ==== rem ====</h3> <p>$ cat rem<br /> <code><br /> #<br /> # Remove Pessoas do Arquivo de Telefones<br /> #</p> <p>grep -v "$1" telefones > /tmp/$$<br /> mv /tmp/$$ telefones<br /> </code></p> <h3> ==== restaura ====</h3> <p>$ cat restaura<br /> <code><br /> #!/bin/bash<br /> #<br /> # Restaura arquivos deletados vi erreeme<br /> #</p> <p>if [ $# -eq 0 ]<br /> then<br /> echo "Uso: $0 <Nome do Arquivo a Ser Restaurado>"<br /> exit 1<br /> fi</p> <p>Dir=`tail -1 /tmp/$LOGNAME/$1`<br /> grep -v $Dir /tmp/$LOGNAME/$1 > $Dir/$1<br /> rm /tmp/$LOGNAME/$1</p> <p></code></p> <h3> ==== rotinas.sh ====</h3> <p>$ cat rotinas.sh<br /> <code><br /> Maquina=""<br /> SN=""<br /> OL=""<br /> function Erro<br /> {<br /> Len=`expr length "$1"`<br /> C=`expr "(" 80 - "$Len" ")" / 2`<br /> tput cup 21 $C<br /> echo "$1\07\c"<br /> 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 <mailto:julio.neves@writeme.com><br /> #==========================================================<br /> #<br /> Num=$(($1 - 1))<br /> AFim=$((1980 + (Num / 365)))<br /> DFim=$((Num % 365 - Num / 1460))<br /> MFim=1<br /> for i in 31 28 31 30 31 30 31 31 30 31 30 31<br /> do<br /> [ $DFim -lt $i ] && break<br /> DFim=$((DFim - i))<br /> MFim=$((MFim + 1))<br /> done<br /> [ $DFim -eq 0 ] &&<br /> {<br /> DFim=29<br /> MFim=2<br /> }<br /> [ $DFim -le 9 ] && echo "0$DFim/\c" || echo "$DFim/\c"<br /> [ $MFim -le 9 ] && echo "0$MFim/\c" || echo "$MFim/\c"<br /> echo $AFim</p> <p>#!/bin/bash<br /> #<br /> #======================================================================<br /> # Calcula qtd dias entre uma data passada como parametro e 01/01/1980.<br /> # Se nao for passado nenhum parametro a data de hoje sera assumida.<br /> # Obs. Para executar este programa sob o sh, trocar os $((..)) por expr<br /> #======================================================================<br /> # Leia: Linux - Programacao Shell ISBN: 85-7452-048-9<br /> # Autor: Julio Cezar Neves <mailto:julio.neves@writeme.com><br /> #======================================================================<br /> #<br /> if [ $1 ]<br /> then<br /> DFim=`echo $1 | cut -f1 -d"/"`<br /> MFim=`echo $1 | cut -f2 -d"/"`<br /> AFim=`echo $1 | cut -f3 -d"/"`<br /> else<br /> DFim=`date +%d`<br /> MFim=`date +%m`<br /> AFim=`date +%Y`<br /> fi</p> <p>TotDias=$((1 + 365 * (AFim - 1980) + (AFim - 1980) / 4))<br /> [ $((AFim % 4)) = 0 -a $MFim -le 2 ] && TotDias=$((TotDias - 1))</p> <p>for i in `echo "31 28 31 30 31 30 31 31 30 31 30 31" | cut -f-$((MFim - 1)) -d" " 2> /dev/null`<br /> do<br /> TotDias=$((TotDias + $i))<br /> done<br /> echo $((TotDias + DFim))</p> <p>Limpa ( )</p> <p>{<br /> tput cup 21 1<br /> echo " "<br /> return<br /> }</p> <p>Mostra ( )</p> <p>{<br /> Mostra=$*<br /> Limpa<br /> Len=`expr length "$Mostra"`<br /> Col=`expr "(" 80 - "$Len" ")" / 2`<br /> tput cup 21 $Col<br /> echo "$Mostra"<br /> }</p> <p>function Cab<br /> {<br /> clear<br /> echo "<br /> +------------+------------+--------------------------------------------+<br /> | | | |<br /> | DATAPREV | TRANSFTP | Producao RJ (821)2347 |<br /> | | | Suporte (821)2338 SP (811)6200 |<br /> +------------+------------+--------------------------------------------+"<br /> }</p> <p>function Div # Faz divisao de inteiros dando resultado com $3 decimais<br /> {<br /> Divid=$1<br /> Divis=$2<br /> Decim=$3<br /> Resp=`expr $Divid / $Divis`,<br /> while [ "$Decim" -gt 0 ]<br /> do<br /> Divid=`expr $Divid % $Divis \* 10`<br /> Resp=$Resp`expr $Divid / $Divis`<br /> Decim=`expr $Decim - 1`<br /> done<br /> return # Quociente editado esta em Resp<br /> }</p> <p>function ChecaPW<br /> {<br /> Lin=$(($1\*4+7))</p> <p> if [ "$2" -eq 1 ]<br /> then<br /> Site=RJ<br /> Maquina=durjcv01<br /> else<br /> Site=SP<br /> Maquina=duspmv01<br /> fi</p> <p> j=1<br /> while true<br /> do<br /> tput cup $Lin $Cwr<br /> echo "Login Name em $Site ($LOGNAME): "<br /> tput cup $Lin $Cre<br /> read User<br /> User=${User:-"$LOGNAME"}<br /> tput cup $Lin $Cre<br /> echo $User<br /> tput cup $(($Lin+2)) $Cwr<br /> echo "Entre com Password em $Site:"<br /> tput cup $(($Lin+2)) $Cre<br /> stty -echo<br /> read PW<br /> stty echo<br /> if [ -z "$PW" ]<br /> then<br /> Pergunta "Deseja continuar" S N<br /> if [ "$SN" = N ]<br /> then<br /> exit<br /> fi<br /> continue<br /> fi<br /> ftp -ivn $Maquina << fimftp > "/tmp/$$" ## So para testar a senha...<br /> user "$User" "$PW"<br /> quit<br /> fimftp<br /> if [ `grep -c "^530 " "/tmp/$$"` -ne 0 ]<br /> then<br /> j=`expr $j + 1`<br /> if [ "$j" -eq 4 ] ## Se em 4 tentativas nao acertar; BYE BYE...<br /> then<br /> Erro "Tentativa de violacao. Programa descontinuado."<br /> rm /tmp/"$$"<br /> exit<br /> fi<br /> Erro "Senha nao confere. Tente outra vez."<br /> continue<br /> fi<br /> break<br /> done<br /> }</p> <p>function LeMaq<br /> {<br /> Lin=$1<br /> Col=$2<br /> if [ "$#" -eq 3 ]<br /> then<br /> MaqDef=$3<br /> fi<br /> while true<br /> do<br /> tput cup $Lin $Col<br /> echo " "<br /> tput cup $Lin $Col<br /> read Maquina<br /> if [ "$#" -eq 3 ]<br /> then<br /> Maquina=${Maquina:-"$MaqDef"}<br /> fi<br /> if [ -z "$Maquina" ]<br /> then<br /> SN "Deseja Abandonar" S N<br /> if [ "$SN" = N ]<br /> then<br /> continue<br /> fi<br /> exit<br /> fi</p> <p> if [ `fgrep -c "$Maquina" /etc/hosts` -eq 0 ]<br /> then<br /> Erro "Nao existe regional com maquina com este nome"<br /> continue<br /> fi<br /> return<br /> done<br /> }</p> <p>function LeOL<br /> {<br /> Col=$1<br /> Lin=$2<br /> 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"<br /> while true<br /> do<br /> tput cup $Lin $Col<br /> echo " "<br /> tput cup $Lin $Col<br /> read OL<br /> if [ -z "$OL" ]<br /> then<br /> SN "Deseja Abandonar" S N<br /> if [ "$SN" = N ]<br /> then<br /> continue<br /> fi<br /> exit<br /> fi</p> <p> if [ `echo "$Maquina" | fgrep -c "$OLs"` -eq 0 ]<br /> then<br /> Erro "Nao existe OL com este numero"<br /> continue<br /> fi<br /> return<br /> done<br /> }<br /> </code></p> <h3> ==== saldo.awk ====</h3> <p>$ cat saldo.awk<br /> <code><br /> #<br /> # Calcula Saldo em Conta Corrente<br /> #<br /> awk '<br /> FILENAME == "creditos" { Saldo[$1] += $2 }<br /> FILENAME == "debitos" { Saldo[$1] -= $2 }<br /> END { for (Nome in Saldo)<br /> print Nome, Saldo [Nome]<br /> }' creditos debitos</p> <p></code></p> <h3> ==== salva_tela.sh ====</h3> <p>$ cat salva_tela.sh<br /> <code><br /> #!/bin/bash<br /> seq 2000 | xargs # Sujando a tela<br /> Lin=$(($(tput lines) / 2)) # Calculando linha e coluna centrais da tela<br /> Col=$(($(tput cols) / 2))<br /> tput cup $Lin; tput el; tput setf 1 # Posicionando, apagando a linha central e colorindo<br /> echo "Em 10 segundos essa tela será fotografada e se apagará"<br /> tput civis # Cursor invisível para melhorar apresentação<br /> for ((i=10; i!=0; i--))<br /> {<br /> tput cup $Lin $Col; tput el # Posiciona no centro da tela e limpa núm anterior<br /> echo $i<br /> sleep 1<br /> }<br /> tput smcup # Tirando uma foto da tela<br /> clear # Poderia ter usado tput reset<br /> tput cup $Lin<br /> echo "Dentro de 10 segundos a tela inicial será recuperada"<br /> 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 </code></p> <h3> ==== talogado ====</h3> <p>$ cat talogado<br /> <code><br /> #<br /> # Verifica se determinado usuario esta "logado" - versao 2<br /> #</p> <p>if who | grep $1 > /dev/null<br /> then<br /> echo $1 esta logado<br /> else<br /> echo $1 nao esta logado<br /> fi<br /> </code></p> <h3> ==== tavazio ====</h3> <p>$ cat tavazio<br /> <code><br /> </code></p> <h3> ==== tecla.sh ====</h3> <p>$ cat tecla.sh<br /> <code><br /> getc ()<br /> {<br /> stty raw<br /> eval $1="`dd bs=1 count=1 2>/dev/null | tr '\015' '\012'`"<br /> stty cooked<br /> }</p> <p>echo "Digite uma opcao: \c"<br /> getc anychar</p> <p>echo \\n\\n\\n$anychar\\n\\n\\n<br /> </code></p> <h3> ==== telef ====</h3> <p>$ cat telef<br /> <code><br /> Ciro<br /> Ney<br /> Enio<br /> Claudia<br /> Paula<br /> Ney<br /> </code></p> <h3> ==== telefones ====</h3> <p>$ cat telefones<br /> <code></p> <p>Ciro Grippi (021)555-1234<br /> Claudia Marcia (021)555-2112<br /> Enio Cardoso (023)232-3423<br /> Juliana Duarte (024)622-2876<br /> Luiz Carlos (021)767-2124<br /> Ney Garrafas (021)988-3398<br /> Ney Gerhardt (024)543-4321<br /> Paula Duarte (011)449-0219<br /> </code></p> <h3> ==== teles ====</h3> <p>$ cat teles<br /> <code><br /> #!/bin/bash</p> <p>#<br /> # Menu do cadastro de telefones - versao 3<br /> #</p> <p>if [ "$#" -ne 0 ]<br /> then<br /> pp "$*"<br /> exit<br /> fi</p> <p>OK=</p> <p>until [ "$OK" ]<br /> do<br /> read Opcao?"</p> <p> Opcao Acao<br /> ===== ====</p> <p> 1 Procurar Alguem<br /> 2 Adicionar Alguem ao Caderno de Telefones<br /> 3 Remover Alguem do Cadastro de Telefones<br /> 4 Listagem do Caderno de Telefones</p> <p> Escolha Uma Das Opcoes Acima (1-4): "<br /> echo "\n"<br /> OK=1<br /> case "$Opcao"<br /> in<br /> 1) read Nome?" Entre com o nome a pesquisar: "<br /> pp "$Nome"<br /> ;;<br /> 2) read Nome?" Nome a ser adicionado: "<br /> read Telef?" Telefone de $Nome: "<br /> add "$Nome" "$Telef"<br /> ;;<br /> 3) read Nome?" Nome a ser removido: "<br /> rem "$Nome"<br /> ;;<br /> 4) lt<br /> ;;<br /> *) echo "Soh sao validas opcoes entre 1 e 4"<br /> OK=<br /> ;;<br /> esac<br /> done<br /> exit<br /> </code></p> <h3> ==== testa_branch.sh ====</h3> <p>$ cat testa_branch.sh<br /> <code><br /> #!/bin/sh<br /> sed -n "<br /> # Se linha vazia, vá pesquisar cadeia<br /> /^$/ b PesqCad<br /> # Senão, acrescenta a linha ao hold buffer<br /> H<br /> # Fim de arquivo também é fim de parágrafo<br /> $ b PesqCad<br /> # Vai para o fim para saltar PesqCad<br /> b<br /> # É aqui que vamos procurar a cadeia no parágrafo<br /> :PesqCad<br /> # Manda todo o parágrafo para o pattern space<br /> x<br /> # Procura a cadeia, se achar imprime<br /> /$1/ p<br /> " $2<br /> </code></p> <h3> ==== testa_sed ====</h3> <p>$ cat testa_sed<br /> <code><br /> 1 # Esta linha nao serah analisada<br /> # A partir daqui, existem linhas vazias<br /> #+ linhas somente com espacos em branco<br /> #+ e linhas com <TABs></p> <p>2 # Esta eh uma linha que deve ser mantida</p> <p>3 # Esta tb deve ser mantida<br /> # Isto eh um <TAB><br /> 4 # Essa tb serah mantida<br /> </code></p> <h3> ==== testchar ====</h3> <p>$ cat testchar<br /> <code><br /> #<br /> # Testa qual o tipo de um caracter recebido por parametro<br /> #</p> <p>##### Teste da Quantidade de Parametros #####<br /> erro=0<br /> if [ "$#" -ne 1 ]<br /> then<br /> echo "Uso: $(basename $0) caractere"<br /> erro=1<br /> fi</p> <p>##### Testa se o 1o. parametro tem o tamanho de um caracter #####<br /> case $1 in<br /> ?) ;;<br /> *) echo "Erro -> Parametro passado deveria ter um caracter"<br /> erro=2<br /> ;;<br /> esac</p> <p>##### Se houve erro o programa termina, passando o codigo do erro #####<br /> if [ "$erro" -ne 0 ]<br /> then<br /> exit $erro<br /> fi</p> <p>case $1 in<br /> [a-z]) echo Letra Minuscula<br /> ;;<br /> [A-Z]) echo Letra Maiuscula<br /> ;;<br /> [0-9]) echo Numero<br /> ;;<br /> *) echo Caracter Especial<br /> ;;<br /> esac<br /> exit 0</p> <p></code></p> <h3> ==== teste ====</h3> <p>$ cat teste<br /> <code><br /> echo $$<br /> </code></p> <h3> ==== testsex ====</h3> <p>$ cat testsex<br /> <code><br /> clear<br /> sexo=$1<br /> if [ "$sexo" -lt 1 -o "(" "$sexo" -gt 2 ")" ]<br /> then<br /> tput cup 21 20<br /> tput smso<br /> echo "Nao sabia que eramos colegas, meu bem!!"<br /> sleep 5<br /> tput rmso<br /> tput reset<br /> exit 1<br /> fi</p> <p>tput bold<br /> tput cup 10 35<br /> if [ "$sexo" -eq 1 ]<br /> then<br /> echo sexo masculino<br /> else<br /> echo sexo feminino<br /> fi</p> <p>sleep 5<br /> tput rmso<br /> tput reset<br /> exit<br /> </code></p> <h3> ==== TiraBranco.sh ====</h3> <p>$ cat TiraBranco.sh<br /> <code><br /> #!/bin/bash<br /> # Renomeia arquivos com espaços nem branco<br /> #+ no nome, trocando-os por sublinhado (_).</p> <p>Erro=0<br /> for Arq in *' '*<br /> do<br /> [ -f ${Arq// /_} ] && {<br /> echo $Arq não foi renomeado<br /> Erro=1<br /> continue<br /> }<br /> mv "$Arq" "${Arq// /_}"<br /> done 2> /dev/null<br /> exit $Erro<br /> </code></p> <h3> ==== toca ====</h3> <p>$ cat toca<br /> <code><br /> Flg=<br /> for i<br /> do<br /> case $i in<br /> -c) Flg=N<br /> ;;<br /> *) if [ -f $i ]<br /> then<br /> ln $i lixo$$<br /> ls -l lixo$$<br /> rm lixo$$<br /> elif [ $Flg ] # Verdadeiro se nao nulo<br /> then<br /> echo \'$i\' nao existe<br /> else<br /> >$i # Cria o arquivo passado com tamanho = zero<br /> fi<br /> ;;<br /> esac<br /> done</p> <p></code></p> <h3> ==== tputcup ====</h3> <p>$ cat tputcup<br /> <code><br /> tput cup 3 6<br /> echo ".<-" tput cup 2 10 echo "/" tput cup 1 12 echo "/" tput cup 0 14 echo "_________ Este eh o ponto (3, 6)" </code></p> <h3> ==== tr ====</h3> <p>$ cat tr<br /> <code><br /> Alpha<br /> </code></p> <h3> ==== trocacase.sh ====</h3> <p>$ cat trocacase.sh<br /> <code><br /> #!/bin/bash<br /> # Se o nome do arquivo tiver pelo menos uma<br /> #+ letra maiúscula, troca-a para minúscula</p> <p>for Arq in *[A-Z]*<br /> do<br /> if [ -f "${Arq,,}" ]<br /> then<br /> echo ${Arq,,} já existe<br /> else<br /> mv "$Arq" "${Arq,,}"<br /> fi<br /> done<br /> </code></p> <h3> ==== tst_exec ====</h3> <p>$ cat tst_exec<br /> <code><br /> exec 1>saida_unica 2>&1<br /> ls $1 || echo O arquivo $1 não existe >&2<br /> echo Fim do programa<br /> </code></p> <h3> ==== tstmatr ====</h3> <p>$ cat tstmatr<br /> <code><br /> while true<br /> do<br /> clear<br /> tput cup 10 15<br /> echo "Entre com sua matricula: \c"<br /> read Matric<br /> if [ ! "$Matric" ]<br /> then<br /> tput cup 12 15<br /> echo "Deseja abandonar? (N/s) \c"<br /> read sn<br /> if [ "$sn" = S -o "(" "$sn" = s ")" ]<br /> then<br /> exit<br /> fi<br /> continue<br /> fi<br /> if expr $Matric + 1 1> /dev/null 2>&1<br /> then<br /> break<br /> else<br /> tput cup 12 15<br /> echo "Matricula Nao Numerica"<br /> read a<br /> continue<br /> fi<br /> done<br /> </code></p> <h3> ==== upperconv.sh ====</h3> <p>$ cat upperconv.sh<br /> <code><br /> #!/bin/bash<br /> # upperconv.sh<br /> # Converte arquivo em maiúscula dando a saída em outro arquivo</p> <p>if [ ! -r "$1" ] # Posso ler arq de entrada?<br /> then<br /> echo Informe arquivo de entrada com direito de leitura<br /> echo Uso: "$0 <Arq. Minusculas> <Arq. Maiúsculas>"<br /> exit 1<br /> fi</p> <p>if [ ! -w "$2" ]<br /> then<br /> echo Informe arquivo de saída com direito de gravação<br /> echo Uso: $0 "<Arq. Minusculas> <Arq. Maiúsculas>"<br /> exit 2<br /> fi</p> <p>exec 4<&0 # Salva stdin no fd 4 exec < $1 # Associa stdin ao arq. em $1 exec 7>&1 # Salva stdout no fd 7<br /> exec > $2 # Associa stdout ao arq. em $2</p> <p># -----------------------------------------------<br /> cat - | tr a-z A-Z # Converte par maiúscula<br /> # ^^^^^ # O hifem sempre representa stdin.<br /> # ^^^^^^^^^^ # Saída do tr para stdout.<br /> # -----------------------------------------------</p> <p>exec 1>&7 7>&- # Restaura stout.<br /> 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 </code></p> <h3> ==== usus ====</h3> <p>$ cat usus<br /> <code><br /> ^bin:<br /> ^irc:<br /> ^root:<br /> ^sys:<br /> ^uucp:<br /> </code></p> <h3> ==== variando ====</h3> <p>$ cat variando<br /> <code><br /> echo a=$a:<br /> a=xx<br /> echo a=$a:<br /> b=`variando1`<br /> echo b=$b</p> <p></code></p> <h3> ==== variando1 ====</h3> <p>$ cat variando1<br /> <code><br /> echo a=$a:<br /> </code></p> <h3> ==== VelEcon ====</h3> <p>$ cat VelEcon<br /> <code><br /> awk 'BEGIN { MinCons=99999 }<br /> {<br /> if ( $2 > MaxVel )<br /> {<br /> CarVel=$1<br /> MaxVel=$2<br /> }<br /> if ( $4 < MinCons ) { CarEcon=$1 MinCons=$4 } } END { print "O",CarVel,"desenvolve",MaxVel,\ "km e\nO",CarEcon,"faz",MinCons,"km/l\n" }' carros </code></p> <h3> ==== velha.sh ====</h3> <p>$ cat velha.sh<br /> <code><br /> #!/bin/bash<br /> #<br /> #######################################################<br /> # JOGO DA VELHA #<br /> # DUVIDO QUE VOCE CONSIGA GANHAR! #<br /> #-----------------------------------------------------#<br /> # TIC TAC TOE #<br /> # I WON'T GIVE YOU A CHANCE. YOU'LL NEVER WIN! #<br /> #######################################################<br /> # #<br /> # Leia: Programacao Shell - Linux #<br /> # Autor: Julio Cezar Neves #<br /> # Editora: Brasport #<br /> # ISBN: 85-7452-076-4 #<br /> # #<br /> #######################################################<br /> # Para qualquer duvida ou esclarecimento sobre este #<br /> # programa estou as ordens em julio.neves@bigfoot.com #<br /> #-----------------------------------------------------#<br /> # Any doubt about this program you can find me at #<br /> # julio.neves@bigfoot.com #<br /> #######################################################<br /> # Se voce estiver sob o bash, troque a 1a. linha por #<br /> # #!/bin/bash #<br /> #-----------------------------------------------------#<br /> # If you are running bash change the 1st. line for #<br /> # #!/bin/bash #<br /> #######################################################<br /> # Este foi um meio divertido que encontrei para #<br /> # testar a compatibilidade no uso de arrays entre o #<br /> # bash e o ksh. Se alguem quiser desenvolver a rotina #<br /> # em que o adversario comeca jogando, sinta-se a #<br /> # vontade, porem nao esqueca de mandar-me o modulo #<br /> # para incorpora-lo ao meu. #<br /> #-----------------------------------------------------#<br /> # This program was developed as a funny way to test #<br /> # the compatibility between arrays in ksh and bash. #<br /> # Feel free for develop the module that the opponent #<br /> # start playing, but don't forget to send me the new #<br /> # routine because I'll attach it at this one. #<br /> #######################################################<br /> #</p> <p>Ganhei=0<br /> Empate=0<br /> Bold=`tput bold`<br /> OBold=`tput sgr0`<br /> Cols=`tput cols`<br /> if [ $Cols -lt 80 -o `tput lines` -lt 25 ]<br /> then<br /> clear<br /> echo "O tamanho minimo da janela deve ser 25 linhas e 80 colunas"<br /> exit 2<br /> read lixo<br /> fi<br /> Col0=`expr \( $Cols - 46 \) / 2`<br /> Eng=`echo "To play in english use: $Bold\`basename $0\`$OBold -e (default language is portuguese)"`</p> <p># Ingles ou Portugues? English or Portuguese?<br /> if [ "$1" = -e ]<br /> then<br /> StrIni[1]=" 1 2 3"<br /> StrIni[2]="1 | | +---------+----------+"<br /> StrIni[3]=" ---+---+--- | Ties | Wins |"<br /> StrIni[4]="2 | | +---------+----------+"<br /> StrIni[5]=" ---+---+--- | | |"<br /> StrIni[6]="3 | | +---------+----------+"<br /> StrGan="I W O N !!!"<br /> StrEmp="T I E"<br /> StrLe="Now it's our time to play (RowColumn):"<br /> StrEr1="At this position already has a -> "<br /> StrEr2="Write row and column together. I.E. 13 means row 1 and column 3"<br /> StrFim="Do you want to continue?"<br /> else<br /> StrIni[1]=" 1 2 3"<br /> StrIni[2]="1 | | +---------+----------+"<br /> StrIni[3]=" ---+---+--- | Empates | Vitorias |"<br /> StrIni[4]="2 | | +---------+----------+"<br /> StrIni[5]=" ---+---+--- | | |"<br /> StrIni[6]="3 | | +---------+----------+"<br /> StrGan="G A N H E I !!!"<br /> StrEmp="E M P A T E"<br /> StrLe="Informe a sua jogada (LinhaColuna):"<br /> StrEr1="Nesta posicao ja existe um -> "<br /> StrEr2="Informe Linha e Coluna juntos. Ex: 13 = Linha 1 e Coluna 3"<br /> StrFim="Deseja continuar?"<br /> fi</p> <p>Escrever ()<br /> {<br /> ColIni=`expr \( $Cols - length "$2" \) / 2`<br /> tput cup $1 $ColIni<br /> echo "$2"<br /> }<br /> Iniciar ()<br /> {<br /> Jogo=<br /> for i in 1 2 3<br /> do<br /> for j in 1 2 3<br /> do<br /> P[$i$j]=<br /> done<br /> done<br /> clear<br /> for i in 1 2 3 4 5 6<br /> do<br /> tput cup `expr 11 + $i` $Col0<br /> echo "${StrIni[i]}"<br /> done<br /> Seg=`date "+%S"`<br /> case `expr $Seg % 5` in<br /> 0) Jogo=11 ; Saida=1 ;;<br /> 1) Jogo=13 ; Saida=2 ;;<br /> 2) Jogo=31 ; Saida=3 ;;<br /> 3) Jogo=33 ; Saida=4 ;;<br /> *) Jogo=22 ; Saida=5 ;;<br /> esac<br /> tput cup 16 `expr $Col0 + 29`<br /> echo $Bold$Empate<br /> tput cup 16 `expr $Col0 + 40`<br /> echo $Ganhei$OBold<br /> }<br /> Jogar ()<br /> {<br /> P[$1]=$2<br /> Lin=`echo $1 | cut -c1`<br /> Col=`echo $1 | cut -c2`<br /> Lin=`expr \( $Lin - 1 \) \* 2 + 13`<br /> Col=`expr \( $Col - 1 \) \* 4 + 3 + $Col0`<br /> tput cup $Lin $Col<br /> echo $2<br /> }<br /> Placar ()<br /> {<br /> tput bold<br /> if [ $1 = E ]<br /> then<br /> Empate=$((Empate+1))<br /> tput cup 22 $Col0<br /> echo "$StrEmp"<br /> tput cup 16 `expr $Col0 + 29` # Escrevendo Placar<br /> echo $Empate<br /> else<br /> Ganhei=$((Ganhei+1))<br /> tput cup 22 $Col0<br /> echo "$StrGan"<br /> tput cup 16 `expr $Col0 + 40` # Escrevendo Placar<br /> echo $Ganhei<br /> case $2 in<br /> L) for j in 1 2 3<br /> do<br /> Jogar $i$j X<br /> done<br /> ;;<br /> C) for j in 1 2 3<br /> do<br /> Jogar $j$i X<br /> done<br /> ;;<br /> D1) for i in 11 22 33<br /> do<br /> Jogar $i X<br /> done<br /> ;;<br /> *) for i in 13 22 31<br /> do<br /> Jogar $i X<br /> done<br /> esac<br /> fi<br /> tput sgr0<br /> }</p> <p># Cuidado com o chefe! WARNING! The boss is near you!<br /> trap "clear ; exit" 0 2 3</p> <p># Jogando Playing<br /> while true<br /> do<br /> Iniciar<br /> if [ "$1" != "-e" ]<br /> then<br /> # tput cup 3 23<br /> Escrever 3 "$Eng"<br /> fi<br /> Jogar $Jogo X<br /> Vez=0<br /> while true<br /> do<br /> if [ $Vez -eq 4 ]<br /> then<br /> Placar E<br /> break<br /> fi<br /> tput cup 21 $Col0<br /> echo "$StrLe"<br /> tput cup 21 `expr $Col0 + 1 + length "$StrLe"`<br /> tput el<br /> tput cup 21 `expr $Col0 + 1 + length "$StrLe"`<br /> read Jogo<br /> case $Jogo in<br /> [1-3][1-3]) if [ ${P[$Jogo]} ]<br /> then<br /> tput cup 22 $Col0<br /> 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 </code></p> <h3> ==== vira ====</h3> <p>$ cat vira<br /> <code><br /> #<br /> # vira - vi resguardando arquivo anterior<br /> # == = =</p> <p>if [ "$#" -ne 1 ]<br /> then<br /> echo "Erro -> Uso: $(basename $0) <arquivo>"<br /> exit 1<br /> fi</p> <p>Arq=$1<br /> if [ ! -f "$Arq" ]<br /> then<br /> vi $Arq<br /> exit 0<br /> fi</p> <p>if [ ! -w "$Arq" ]<br /> then<br /> echo "Voce nao tem direito de gravacao em $Arq"<br /> exit 2<br /> fi</p> <p>cp -f $Arq $Arq~<br /> vi $Arq<br /> exit 0<br /> </code></p> <div class="printfriendly pf-alignleft"><a href="http://www.printfriendly.com/print?url=http%3A%2F%2Fwww.livrate.com.br%2F%3Fp%3D217" rel="nofollow" onclick="window.print(); return false;"><img style="border:none;-webkit-box-shadow:none; box-shadow:none;" src="http://cdn.printfriendly.com/button-print-blu20.png" alt="Print Friendly" /></a></div></div> <p class="meta_tags"></p> <p></p> </div> <div class="clear"></div> <div class="form"> <div class="comments"> <p></p> <div id="respond" class="comment-respond"> <h3 id="reply-title" class="comment-reply-title">Leave a Reply <small><a rel="nofollow" id="cancel-comment-reply-link" href="/?p=217#respond" style="display:none;">Cancel reply</a></small></h3> <form action="http://www.livrate.com.br/wp-comments-post.php" method="post" id="commentform" class="comment-form"> <p class="comment-notes">Your email address will not be published. Required fields are marked <span class="required">*</span></p> <p class="comment-form-author"><label for="author">Name <span class="required">*</span></label> <input id="author" name="author" type="text" value="" size="30" aria-required='true' /></p> <p class="comment-form-email"><label for="email">Email <span class="required">*</span></label> <input id="email" name="email" type="text" value="" size="30" aria-required='true' /></p> <p class="comment-form-url"><label for="url">Website</label> <input id="url" name="url" type="text" value="" size="30" /></p> <p class="comment-form-comment"><label for="comment">Comment</label> <textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p> <p class="form-allowed-tags">You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <code><a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> </code></p> <p class="form-submit"> <input name="submit" type="submit" id="submit" value="Post Comment" /> <input type='hidden' name='comment_post_ID' value='217' id='comment_post_ID' /> <input type='hidden' name='comment_parent' id='comment_parent' value='0' /> </p> <input type="hidden" id="ct_checkjs_f340f1b1f65b6df5b5e3f94d95b11daf" name="ct_checkjs" value="0" /><script type="text/javascript">var ct_input_name = 'ct_checkjs_f340f1b1f65b6df5b5e3f94d95b11daf';var ct_input_value = document.getElementById(ct_input_name).value;document.getElementById(ct_input_name).value = document.getElementById(ct_input_name).value.replace(ct_input_value, '1750019752');</script> </form> </div><!-- #respond --> </div> </div> </article> </div> </div> <div class="page_sidebar"> <div class="gutter"> <aside id="text-2" class="widget widget_text"> <div class="textwidget"><img class="alignnone size-medium wp-image-96" src="http://www.livrate.com.br/wp-content/uploads/2014/06/livrate-azul1-258x300.png" alt="livrate-azul" width="150" height="200" /></div> </aside><aside id="search-2" class="widget widget_search"> <h3 class="widget-title">Pesquista</h3><hr><form role="search" method="get" id="searchform" class="searchform" action="http://www.livrate.com.br/"> <div> <label class="screen-reader-text" for="s">Search for:</label> <input type="text" value="" name="s" id="s" /> <input type="submit" id="searchsubmit" value="Search" /> </div> </form></aside><aside id="categories-2" class="widget widget_categories"> <h3 class="widget-title">Categorias</h3><hr> <ul> <li class="cat-item cat-item-4"><a href="http://www.livrate.com.br/?cat=4" >Bacula</a> </li> <li class="cat-item cat-item-6"><a href="http://www.livrate.com.br/?cat=6" >Eventos</a> </li> <li class="cat-item cat-item-3"><a href="http://www.livrate.com.br/?cat=3" >Fotos</a> </li> <li class="cat-item cat-item-7"><a href="http://www.livrate.com.br/?cat=7" >Palestras</a> </li> <li class="cat-item cat-item-5"><a href="http://www.livrate.com.br/?cat=5" >shell</a> </li> <li class="cat-item cat-item-2"><a href="http://www.livrate.com.br/?cat=2" >Treinamentos</a> </li> <li class="cat-item cat-item-1"><a href="http://www.livrate.com.br/?cat=1" >Uncategorized</a> </li> </ul> </aside> <aside id="recent-posts-2" class="widget widget_recent_entries"> <h3 class="widget-title">Posts Recentes</h3><hr> <ul> <li> <a href="http://www.livrate.com.br/?p=299">Treinamento SERPRO – Recife</a> </li> <li> <a href="http://www.livrate.com.br/?p=285">Latinoware 2014: “Meu deus do Shell!”</a> </li> <li> <a href="http://www.livrate.com.br/?p=281">Palestra FISL 15: Júlio Neves – Assim na terra como no shell</a> </li> <li> <a href="http://www.livrate.com.br/?p=246">teste caixa</a> </li> <li> <a href="http://www.livrate.com.br/?p=217">Exercícios e Exemplos do Livro</a> </li> </ul> </aside><aside id="recent-comments-2" class="widget widget_recent_comments"> <h3 class="widget-title">Comentários Recentes</h3><hr><ul id="recentcomments"></ul></aside><aside id="archives-2" class="widget widget_archive"> <h3 class="widget-title">Arquivos</h3><hr> <ul> <li><a href='http://www.livrate.com.br/?m=201504'>April 2015</a></li> <li><a href='http://www.livrate.com.br/?m=201411'>November 2014</a></li> <li><a href='http://www.livrate.com.br/?m=201406'>June 2014</a></li> <li><a href='http://www.livrate.com.br/?m=201405'>May 2014</a></li> </ul> </aside><aside id="meta-2" class="widget widget_meta"> <h3 class="widget-title">Meta</h3><hr> <ul> <li><a href="http://www.livrate.com.br/wp-login.php">Log in</a></li> <li><a href="http://www.livrate.com.br/?feed=rss2">Entries <abbr title="Really Simple Syndication">RSS</abbr></a></li> <li><a href="http://www.livrate.com.br/?feed=comments-rss2">Comments <abbr title="Really Simple Syndication">RSS</abbr></a></li> <li><a href="https://wordpress.org/" title="Powered by WordPress, state-of-the-art semantic personal publishing platform.">WordPress.org</a></li> </ul> </aside> </div> </div> </div> </div> </div> </div> <footer id="footer"> <div class="container"> <div class="footer_widgets columnwrapp clearfix"> <div class="column4"> <aside class="widget"> <h3 class="widget-title">Recent Posts</h3> <ul> <li><a href='http://www.livrate.com.br/?p=299'>Treinamento SERPRO – Recife</a></li> <li><a href='http://www.livrate.com.br/?p=285'>Latinoware 2014: “Meu deus do Shell!”</a></li> <li><a href='http://www.livrate.com.br/?p=281'>Palestra FISL 15: Júlio Neves – Assim na terra como no shell</a></li> <li><a href='http://www.livrate.com.br/?p=246'>teste caixa</a></li> <li><a href='http://www.livrate.com.br/?p=217'>Exercícios e Exemplos do Livro</a></li> <li><a href='http://www.livrate.com.br/?p=160'>Teste</a></li> <li><a href='http://www.livrate.com.br/?p=120'>Papo de Botequim – Parte I</a></li> <li><a href='http://www.livrate.com.br/?p=108'>O que é o Bacula?</a></li> <li><a href='http://www.livrate.com.br/?p=1'>Treinamento Bacula ITA (São José dos Campos/2014)</a></li> </ul> </aside> </div> <div class="column4"> <aside class="widget"> <h3 class="widget-title">Tag Cloud</h3> <div class="tagcloud"> </div> </aside> </div> <div class="column4"> <aside class="widget"> <h3 class="widget-title">Pages</h3> <ul> <li class="page_item page-item-14"><a href="http://www.livrate.com.br/">Início</a></li> <li class="page_item page-item-304"><a href="http://www.livrate.com.br/?page_id=304">Sobre</a></li> <li class="page_item page-item-12 current_page_parent"><a href="http://www.livrate.com.br/?page_id=12">Blog</a></li> <li class="page_item page-item-5"><a href="http://www.livrate.com.br/?page_id=5">Treinamentos In-Company</a></li> <li class="page_item page-item-20"><a href="http://www.livrate.com.br/?page_id=20">Livros dos Instrutores</a></li> <li class="page_item page-item-105"><a href="http://www.livrate.com.br/?page_id=105">Outros Treinamentos</a></li> </ul> </aside> </div> <div class="column4"> <aside class="widget"> <h3 class="widget-title">Categories</h3> <ul> <li class="cat-item cat-item-4"><a href="http://www.livrate.com.br/?cat=4" >Bacula</a> </li> <li class="cat-item cat-item-6"><a href="http://www.livrate.com.br/?cat=6" >Eventos</a> </li> <li class="cat-item cat-item-3"><a href="http://www.livrate.com.br/?cat=3" >Fotos</a> </li> <li class="cat-item cat-item-7"><a href="http://www.livrate.com.br/?cat=7" >Palestras</a> </li> <li class="cat-item cat-item-5"><a href="http://www.livrate.com.br/?cat=5" >shell</a> </li> <li class="cat-item cat-item-2"><a href="http://www.livrate.com.br/?cat=2" >Treinamentos</a> </li> <li class="cat-item cat-item-1"><a href="http://www.livrate.com.br/?cat=1" >Uncategorized</a> </li> </ul> </aside> </div> </div> <div class="copyright_container clearfix"> <p class="copyright">Copyright © 2015</p> <p class="credit_footer">Theme created by <a href="http://www.pwtthemes.com/theme/honma-free-responsive-wordpress-theme">PWT</a>. Powered by <a href="http://wordpress.org/">WordPress.org</a> </p> </div> </div> </footer> </div> <script type="text/javascript"> var pfHeaderImgUrl = ''; var pfHeaderTagline = ''; var pfdisableClickToDel = '0'; var pfHideImages = '0'; var pfImageDisplayStyle = 'right'; var pfDisableEmail = '0'; var pfDisablePDF = '0'; var pfDisablePrint = '0'; var pfCustomCSS = ''; (function() { var e = document.createElement('script'); e.type="text/javascript"; if('https:' == document.location.protocol) { js='https://pf-cdn.printfriendly.com/ssl/main.js'; } else{ js='http://cdn.printfriendly.com/printfriendly.js'; } e.src = js; document.getElementsByTagName('head')[0].appendChild(e); })(); </script> <script type='text/javascript' src='http://www.livrate.com.br/wp-content/themes/honma/js/main.js?ver=1.0'></script> <script type='text/javascript' src='http://www.livrate.com.br/wp-includes/js/comment-reply.min.js?ver=4.0.31'></script> <script type='text/javascript' src='http://www.livrate.com.br/wp-includes/js/jquery/ui/jquery.ui.effect.min.js?ver=1.10.4'></script> <script type='text/javascript' src='http://www.livrate.com.br/wp-includes/js/jquery/ui/jquery.ui.effect-blind.min.js?ver=1.10.4'></script> <script type='text/javascript'> /* <![CDATA[ */ var stbUserOptions = []; stbUserOptions = {"mode":"css","cssOptions":{"roundedCorners":false,"mbottom":10,"imgHide":"http:\/\/www.livrate.com.br\/wp-content\/stb-themes\/stb-metro\/minus.png","imgShow":"http:\/\/www.livrate.com.br\/wp-content\/stb-themes\/stb-metro\/plus.png","strHide":"Hide","strShow":"Show"}};; /* ]]> */ </script> <script type='text/javascript' src='http://www.livrate.com.br/wp-content/plugins/wp-special-textboxes/js/wstb.min.js?ver=5.2.91'></script> </body> </html>
";
$config_tmp{$ROOT}{"tr"}="